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.
Note: You are not suppose to use the library's sort function for this problem.
It's actually Dutch national flag problem.
[, i): 0
[i, j]: 1
(k, ...]: 2
Once j meets k, the sorting is complete
class Solution {
public:
void sortColors(vector<int>& nums) {
int i=0, j=i, k=nums.size()-1;
while(j<=k)
{
if(nums[j]==0) swap(nums[i++], nums[j++]);
else if(nums[j]==1) j++;
//还不知道j交换之后是什么元素,因此未移动j
else swap(nums[j], nums[k--]);
}
}
};