输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
解题思路
- 暴力方法
显然,我们可以通过遍历将元素中的每个元素进行判断,如果是奇数,我们插入辅助数组的前端,前指针自增;如果是偶数,我们插入辅助数组的后端,尾指针自增。
class Solution {
public int[] exchange(int[] nums) {
int[] res = new int[nums.length];
int head = 0, tail = nums.length - 1;
for (int i : nums) {
if (i % 2 == 0) {
res[tail--] = i;
} else res[head++] = i;
}
return res;
}
}
- 不需要额外空间的方法
我们使用首尾指针,移动首指针到指向一个偶数,然后移动尾指针直到指向一个奇数,交换两个指针指向的值。重复,直到两个指针指向同一个元素。相较于暴力解法节约了空间。
class Solution {
public int[] exchange(int[] nums) {
int head = 0, tail = nums.length - 1;
while (head < tail){
if (nums[head]%2!=0){
head++;
continue;
}
if (nums[tail]%2==0){
tail--;
continue;
}
int temp = nums[head];
nums[head] = nums[tail];
nums[tail] = temp;
}
return nums;
}
}