Sort an Array Containing Only 0s, 1s, and 2s
Implement sortZerosOnesTwos
You're given an array
nums that contains only the values 0, 1, and 2, mixed together in no particular order. Rearrange it in place so every 0 comes before every 1, and every 1 comes before every 2.
Try to do it in a single pass, without calling a general-purpose sort — a three-way partition with three pointers gets you there in O(n) time and O(1) extra space.
Example 1:
Input: nums = [2,0,1,2,1,0]
Output: [0,0,1,1,2,2]
Example 2:
Input: nums = [1,1,1]
Output: [1,1,1]
Example 3:
Input: nums = [0,2]
Output: [0,2]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ nums.length ≤ 10⁵ - ●
nums[i] is 0, 1, or 2
nums =
[2, 0, 1, 2, 1, 0]