CS-Notes/notes/21. 调整数组顺序使奇数位于偶数前面.md
2021-03-23 02:48:19 +08:00

65 lines
1.7 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 21. 调整数组顺序使奇数位于偶数前面
## 题目链接
[牛客网](https://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b?tpId=13&tqId=11166&tab=answerKey&from=cyc_github)
## 题目描述
需要保证奇数和奇数偶数和偶数之间的相对位置不变这和书本不太一样例如对于 [1,2,3,4,5]调整后得到 [1,3,5,2,4]而不能是 {5,1,3,4,2} 这种相对位置改变的结果
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d03a2efa-ef19-4c96-97e8-ff61df8061d3.png" width="200px"> </div><br>
## 解题思路
方法一创建一个新数组时间复杂度 O(N)空间复杂度 O(N)
```java
public int[] reOrderArray (int[] nums) {
// 奇数个数
int oddCnt = 0;
for (int x : nums)
if (!isEven(x))
oddCnt++;
int[] copy = nums.clone();
int i = 0, j = oddCnt;
for (int num : copy) {
if (num % 2 == 1)
nums[i++] = num;
else
nums[j++] = num;
}
return nums;
}
private boolean isEven(int x) {
return x % 2 == 0;
}
```
方法二使用冒泡思想每次都将当前偶数上浮到当前最右边时间复杂度 O(N<sup>2</sup>)空间复杂度 O(1)时间换空间
```java
public int[] reOrderArray(int[] nums) {
int N = nums.length;
for (int i = N - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (isEven(nums[j]) && !isEven(nums[j + 1])) {
swap(nums, j, j + 1);
}
}
}
return nums;
}
private boolean isEven(int x) {
return x % 2 == 0;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
```