2019-11-02 12:07:41 +08:00
|
|
|
|
# 21. 调整数组顺序使奇数位于偶数前面
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/beb5aa231adc45b2a5dcc5b62c93f593?tpId=13&tqId=11166&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
需要保证奇数和奇数,偶数和偶数之间的相对位置不变,这和书本不太一样。
|
|
|
|
|
|
2019-12-06 00:29:51 +08:00
|
|
|
|
<div align="center"> <img src="pics/d03a2efa-ef19-4c96-97e8-ff61df8061d3.png" width="200px"> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
方法一:创建一个新数组,时间复杂度 O(N),空间复杂度 O(N)。
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public void 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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private boolean isEven(int x) {
|
|
|
|
|
return x % 2 == 0;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
方法二:使用冒泡思想,每次都当前偶数上浮到当前最右边。时间复杂度 O(N<sup>2</sup>),空间复杂度 O(1),时间换空间。
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public void 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);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
```
|
2019-11-02 14:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|