Prove safety Offer -. 13 to adjust the order of the array so that in front of the even-odd

Title Description

Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all the odd part of the front half of the array, is located in the second half of all the even array, and between odd and ensure a relatively even, odd and even the same position. This book is not the same.

Problem-solving ideas

Copy Copy a new array [], then the statistics of the number of array odd, an even number as a new starting index, and then an odd set index (0), a new copy of the array traversal, maintaining two pointers, odd press even number are inserted.

public void reOrderArray(int[] nums) {
    // 奇数个数
    int oddCnt = 0;
    for (int val : nums)
        if (val % 2 == 1)
            oddCnt++;
    int[] copy = nums.clone();
    int i = 0, j = oddCnt;
    for (int num : copy) {
        if (num % 2 == 1)
            nums[i++] = num;
        else
            nums[j++] = num;
    }
}

Guess you like

Origin www.cnblogs.com/xiehang/p/11293931.html