Problem
The entries of nums encode three colors as 0, 1, and 2. Rearrange the supplied array in place so all 0s come first, followed by all 1s, then all 2s. Keep the count of each value unchanged. Using a library sorting function is forbidden.
void sortColors(vector<int>& nums);
The displayed result is the changed argument; the function returns no array.
Examples
Input: nums = [1,2,0,1,0]
Array after call: [0,0,1,1,2]
Input: nums = [2,2,0,0]
Array after call: [0,0,2,2]
Constraints
-
1 <= nums.length <= 300
.
-
Each value is 0, 1, or 2, representing red, white, or blue respectively.
-
Mutate the array in place without calling a library sort.
Source follow-up
Can you do this in one pass with constant extra space?