diff --git a/notes/21. 调整数组顺序使奇数位于偶数前面.md b/notes/21. 调整数组顺序使奇数位于偶数前面.md index 13ca98e5..6691d3fb 100644 --- a/notes/21. 调整数组顺序使奇数位于偶数前面.md +++ b/notes/21. 调整数组顺序使奇数位于偶数前面.md @@ -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 原题不要求保证奇数和偶数各自的相对位置不变。

## 解题思路 -方法一:创建一个新数组,时间复杂度 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(N2),空间复杂度 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; } ```