Niuke.com brush questions | Adjust the order of the array so that the odd numbers come before the even numbers

Topic source: Niuke.com
programming link

Topic description:

Input an array of integers, implement a function to adjust the order of the numbers in the array, so that all odd numbers are in the first half of the array, all even numbers are in the second half of the array, and keep odd and odd, even and even numbers between The relative position remains unchanged.

answer:

Note that the title requires the relative position to remain unchanged, so it is best to use an auxiliary array to do it.
First traverse the original array, record the number of odd numbers, create a new
array , traverse the original array again, put the odd number in front of the new array, and put the even number after the odd number (behind the array) and
finally exchange the array, Just make the original array equal to the auxiliary array

Code:

class Solution {
public:
    void reOrderArray(vector<int> &array) {
        int cnt =0;
        int len = array.size();
        for(int i=0;i<array.size();cnt +=(array[i++]&0x01)); //奇数的个数
        vector<int>arr(len);
        for(int i=0,k=0,j=cnt;i<len;i++)
        {
            array[i]&0x01? arr[k++] = array[i]:arr[j++] = array[i];
        }
        array.swap(arr);
    }
};

Running time: 3ms Memory usage: 484k

If there is no condition that the relative position does not change, only one array can be used. Use two pointers, pointing to the front and back of the array, respectively. The first one stops when it encounters an even number, and the latter one stops when it encounters an odd number. After the two are exchanged, they continue. The code is as follows:

class Solution {
public:
    void reArray(vector<int> &array) {
        int head = 0, tail = array.size() - 1;
        while (head < tail) {
            for (; head < tail && array[head] % 2; head++);//遇到偶数停下
            for (; head < tail && !(array[tail] % 2); tail--);//遇到奇数停下
            if (head < tail)
                swap(array[head++], array[tail--]);//交换,改变了相对位置
        }
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325568210&siteId=291194637