剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

剑指 Offer 21. 调整数组顺序使奇数位于偶数前面

相向双指针

class Solution {
    public int[] exchange(int[] nums) {
        int l = 0, r = nums.length - 1;
        while(l < r){
            while(l < r && (nums[l] & 1) == 1) l++;
            while(l < r && (nums[r] & 1) == 0) r--;
            int tmp = nums[l];
            nums[l] = nums[r];
            nums[r] = tmp;
        }
        return nums;
    }
}

同向双指针(快慢双指针)

class Solution {
    public int[] exchange(int[] nums) {
        for(int slow = 0, fast = 0; fast < nums.length; fast++){
            if((nums[fast] & 1) == 1){
                int tmp = nums[fast];
                nums[fast] = nums[slow];
                nums[slow] = tmp;
                slow++;
            }
        }
        return nums;
    }
}

你可能感兴趣的:(#,剑指offer,算法)