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

双指针

public int[] exchange(int[] nums) {
        int len = nums.length;
        int[] res = new int[len];
        int j = 0, k = len-1;
        for (int num : nums) {
            if ((num & 0x1) == 1) {//奇数
                res[j++] = num;
            }else {
                res[k--] = num;
            }
        }
        return res;
    }


方法二:

在原数组上用双指针,并且进行交换

class Solution {
    public int[] exchange(int[] nums) {
        int len = nums.length;
        int i = 0,j = len-1;
        while(i<j){
            if((nums[i]&0x1) != 1 && (nums[j]&0x1) == 1){
                int temp = nums[i];
                nums[i] = nums[j];
                nums[j] = temp;
            }
            while(i<len && (nums[i]&0x1) == 1){
                i++;
            }
            while(j>=0 && (nums[j]&0x1) != 1){
                j--;
            }
        }
        return nums;
    }
}

我的前方是万里征途,星辰大海!!
原文地址:https://www.cnblogs.com/taoyuxin/p/13470174.html