Given an array with n objects colored red, white or blue, sort them 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.
class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.empty())
return;
int start = 0;
int current = start;
int end = nums.size()-1;
while(current<=end)
{
if(nums[current] == 0)
{
if(nums[start]!=nums[current])
{
int temp = nums[start];
nums[start] = 0 ;
nums[current] = temp;
}
start++;
current++;
}else if(nums[current] == 1)
{
current++;
}else{
if(nums[current]!=nums[end])
{
int temp = nums[end];
nums[end] = 2;
nums[current] = temp;
}
end --;
}
}
return;
}
};
注:nums[current] == 1时,start++, current++是因为前面已经排好序,nums[current] == 2, end --,后面没有排好序,还需要继续判断。