Update 21. 调整数组顺序使奇数位于偶数前面.md

题目链接改为力扣中的对应题目,该题不要求保持相对顺序,补充首尾双指针的解法。
This commit is contained in:
CyC2018
2026-10-28 13:45:04 +08:00
parent 8c9f4191b5
commit 616bbadb77
@@ -2,63 +2,52 @@
## 题目链接
[牛客网](https://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b?tpId=13&tqId=11166&tab=answerKey&from=cyc_github)
[Leetcode](https://leetcode.cn/problems/diao-zheng-shu-zu-shun-xu-shi-qi-shu-wei-yu-ou-shu-qian-mian-lcof/)
## 题目描述
需要保证奇数和奇数,偶数和偶数之间的相对位置不变,这和书本不太一样。例如对于 [1,2,3,4,5],调整后得到 [1,3,5,2,4],而不能是 {5,1,3,4,2} 这种相对位置改变的结果。
将所有奇数调整到偶数之前。LeetCode 原题不要求保证奇数和偶数各自的相对位置不变。
<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)。
### 方法一:双指针(不要求相对顺序)
使用首尾双指针,左指针寻找偶数,右指针寻找奇数,找到后交换位置。时间复杂度 O(N),空间复杂度 O(1)。
```java
public int[] reOrderArray (int[] nums) {
// 奇数个数
public int[] trainingPlan(int[] actions) {
int i = 0, j = actions.length - 1;
while (i < j) {
while (i < j && actions[i] % 2 == 1) i++;
while (i < j && actions[j] % 2 == 0) j--;
int t = actions[i];
actions[i] = actions[j];
actions[j] = t;
}
return actions;
}
```
### 方法二:新建数组(保持相对顺序)
如果需要保证奇数之间、偶数之间的相对位置不变,可以先统计奇数个数,再借助新数组按顺序存放。时间复杂度 O(N),空间复杂度 O(N)。
```java
public int[] trainingPlan(int[] actions) {
int oddCnt = 0;
for (int x : nums)
if (!isEven(x))
for (int x : actions)
if (x % 2 == 1)
oddCnt++;
int[] copy = nums.clone();
int[] copy = actions.clone();
int i = 0, j = oddCnt;
for (int num : copy) {
if (num % 2 == 1)
nums[i++] = num;
actions[i++] = num;
else
nums[j++] = num;
actions[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;
return actions;
}
```