75

Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

  • O(1) space , one pass
    • first assign all element to 2, =>
    • then we check if the current element is smaller than 2, if it is, it could be 1 or 0, then assign the element to 1, =>
    • then we check if the current element is 0, if it is, then assign the element to 0;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void (vector<int>& nums) {
for(int i = 0, j = 0, k = 0; k < nums.size(); k++){
int temp = nums[k];
nums[k] = 2;
if(temp < 2){
nums[j] = 1;
j++;
}
if(temp < 1){
nums[i] = 0;
i++;
}
}
}