[Prove safety face questions] 21. Offer adjusted so that the array sequentially in front of even-odd

topic

Enter an array of integers, to realize a function to adjust the order of the numbers in the array, such that all of the odd part of the front half of the array, all the even located in the second half of the array.

Example:

输入:nums = [1,2,3,4]
输出:[1,3,2,4] 
注:[3,1,2,4] 也是正确的答案之一。

prompt:

  • 1 <= nums.length <= 50000
  • 1 <= nums[i] <= 10000

Thinking

Code

Time complexity: O (n)
complexity of space: O (1)

class Solution {
public:
    vector<int> exchange(vector<int>& nums) {
        int i = 0, j = nums.size() - 1;
        while (i < j) {
            while (i < j && nums[i] % 2 == 1) ++i;
            while (i < j && nums[j] % 2 == 0) --j;
            swap(nums[i], nums[j]);
        }
        return nums;
    }
};

Guess you like

Origin www.cnblogs.com/galaxy-hao/p/12639293.html