Categories:

Tags:



Problem

Given an array of integers nums, half of the integers in nums are odd, and the other half are even.

Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.

Return any answer array that satisfies this condition.

Constraints

  • 2 <= nums.length <= 2 * 104
  • nums.length is even.
  • Half of the integers in nums are even.
  • 0 <= nums[i] <= 1000

Solution

The problem Sort Array By Parity II can be solved using the technique from Sort Array By Parity, except this time we swap odd numbers in even indexes with even elements in odd indexes.

Implementation

static const int fast_io = []()
{
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution
{
  public:
    vector<int> sortArrayByParityII(vector<int> &nums)
    {
        int even = 0, odd = 1;
        while (even < nums.size() && odd < nums.size())
        {
            if (nums[even] % 2 == 0)
                even += 2;
            else if (nums[odd] % 2)
                odd += 2;
            else
                swap(nums[even], nums[odd]);
        }

        return nums;
    }
};