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.
解答:
设定一个red指针指向开头,一个blue指针指向结尾。然后用i遍历,如果遇到0
,那么与red交换,如果遇到2,那么与blue交换。如果遇到1,那么不用交换。应该注意到:
1.与blue交换后,i–
2. 与i是遍历到blue的。
class Solution {
public:
void sortColors(vector<int>& nums) {
int i=0;int red=0;int blue=nums.size()-1;
if(nums.size()==1) return;
for(int i=0;i<=blue;i++)
{
if(nums[i]==0)
swap(nums[red++],nums[i]);
else if(nums[i]==2)
swap(nums[blue--],nums[i--]);
}
}
};