输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。
示例:
输入:nums = [1,2,3,4]
输出:[1,3,2,4]
注:[3,1,2,4] 也是正确的答案之一。
提示:
1 <= nums.length <= 50000
1 <= nums[i] <= 10000
面试题KeyNote.002
面试题KeyNote.003
面试题KeyNote.004
面试题KeyNote.005
面试题KeyNote.006
面试题KeyNote.007
面试题KeyNote.008
面试题KeyNote.009
面试题KeyNote.010
面试题KeyNote.011
面试题KeyNote.012
面试题KeyNote.013
面试题KeyNote.014
面试题KeyNote.015
面试题KeyNote.016
面试题KeyNote.017
class Solution {
public int[] exchange(int[] nums) {
// 定义头指针 left ,尾指针 right ,临时变量 tmp
int left = 0, right = nums.length - 1, tmp;
//重复操作,直到 left == right 为止
while(left < right) {
// nums[left] & 1 与 nums[right] & 1 都是用来判断数字奇偶性。
// left 一直往右移,直到它指向的值为偶数
while(left < right && (nums[left] & 1) == 1) left++;
// right 一直往左移, 直到它指向的值为奇数
while(left < right && (nums[right] & 1) == 0) right--;
// 交换 nums[left] 和 nums[right]*
tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
}
return nums;
}
}
时间复杂度为 O(N) ,其中 N 为数组 nums 的长度。
空间复杂度为 O(1)