双指针:
left 一直往右移,直到它指向的值为偶数,right 一直往左移, 直到它指向的值为奇数。交换完后左指针一定指的是奇数,右指针一定指的是偶数,故为了优化代码,可以 left++,right–以减少遍历次数。
class Solution {
public int[] exchange(int[] nums) {
int left = 0, right = nums.length - 1;
while(left < right){
// 如果是奇数,左指针右移
if ((nums[left] & 1) == 1){
left++;
continue;
}
// 如果是偶数,右指针左移
if ((nums[right] & 1) == 0){
right--;
continue;
}
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
return nums;
}
}
快慢指针:slow指向奇数应该存放的位置,fast向前搜索奇数。
fast 向前移动,当它搜索到奇数时,将它和 nums[low] 交换,此时 low 向前移动一个位置 .
class Solution {
public int[] exchange(int[] nums) {
int slow = 0, fast = 0;
while(fast < nums.length){
if((nums[fast] & 1) == 1){
int temp = nums[fast];
nums[fast] = nums[slow];
nums[slow] = temp;
slow++;
}
fast++;
}
return nums;
}
}