Categories:

Tags:



Problem

Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers.

Return any array that satisfies this condition.

Constraints

  • 1 <= nums.length <= 5000
  • 0 <= nums[i] <= 5000

Solution

The problem Sort Array By Parity can be solved by swapping odd integers from the left with even integers from the right.

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> sortArrayByParity(vector<int> &nums)
    {
        int left = 0, right = nums.size() - 1;
        while (left < right)
        {
            if (nums[left] % 2 == 0)
                left += 1;
            else if (nums[right] % 2)
                right -= 1;
            else
                swap(nums[left++], nums[right--]);
        }

        return nums;
    }
};