辅助数组

  • 使用辅助数组,保存偶数值
  • 移动奇数值覆盖前面的zhi,再将辅助数组的偶数值复制回原数组
public class Solution {
    public void reOrderArray(int[] array) {
        int[] cache = new int[array.length];
        int i = 0;
        // 保存偶数
        for(int num : array) {
            if(num % 2 == 0) {
                cache[i++] = num;
            }
        }
        int j = 0;
        // 移动奇数
        for(int num : array) {
            if(num % 2 == 1) {
                array[j++] = num;
            }
        }
        i = 0;
        // 复制偶数
        while(j < array.length) {
            array[j++] = cache[i++];
        }
    }
}

逐位移动

  • 遍历数组,碰到偶数值就记录个数j,每个奇数都要前移j位(不是覆盖)
public class Solution {
    public void reOrderArray(int[] array) {
        int[] cache = new int[array.length];
        int even = 0;
        for(int i = 0; i < array.length; i++) {
            // 记录偶数个数
            if((array[i] & 1) == 0) {
                even++;
            // 奇数前移even位
            } else {
                int temp = array[i];
                for(int j = i; j > i - even; j--) {
                    array[j] = array[j - 1];
                }
                array[i - even] = temp;
            }
        }
    }
}