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.
Example 1:
Input: nums = [3,1,2,4]
Output: [2,4,3,1]
Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
1 <= nums.length <= 5000
0 <= nums[i] <= 5000
Solutions
Solution 1: Two Pointers
Thinking
Even numbers should precede odds; relative order is free. An extra array would work, but the permutation can be done in place. Two pointers move inward: advance the left on an even, the right on an odd, otherwise swap. Each index is visited a constant number of times.
We use two pointers \(i\) and \(j\) to point to the beginning and end of the array respectively. When \(i < j\), we perform the following operations.
If \(nums[i]\) is even, then increment \(i\) by \(1\).
If \(nums[j]\) is odd, then decrement \(j\) by \(1\).
If \(nums[i]\) is odd and \(nums[j]\) is even, then swap \(nums[i]\) and \(nums[j]\). Then increment \(i\) by \(1\), and decrement \(j\) by \(1\).
Finally, return the array \(nums\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(nums\). The space complexity is \(O(1)\).