Question:
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.
Note:
You are not suppose to use the library's sort function for this problem.
题目意思是,0---红色,1---白色,2----蓝色。不能用模板中自带的sort方法,使得数组中的颜色按照红白蓝色排序。
只有三种颜色,所以只要依次将0排在前,1排在前即可,不用刻意排2,已经在后面了;
实现方法,设置两个指针left,right;初始化数组的头和尾。
1、依次判断left指向的数据是不是0,是left++,不是,交换从后面数第一个0,然后--right和++left;
2、重置right为原数组的尾,left接上面的值,从left开始判断,left指向的值是不是1,是++left,不是则和后面数第一个1交换。
代码如下:
<span style="font-size:14px;">class Solution {
public:
void sortColors(vector<int>& nums) {
if(nums.size() <= 1){
return ;
}
int left = 0;
int right = nums.size()-1;
vector<int>::iterator it;
for(int i = 0; i < 2; ++i){
it = find(nums.begin()+left,nums.end(),i);
if(it == nums.end())
continue;
while(left < right){
if(nums[left] <= i){
++left;
}
else{
int t = nums[left];
while(nums[right] != i && right > left)
--right;
if(left == right)
continue;
else{
nums[left] = i;
nums[right] = t;
++left;
--right;
}
}
}
right = nums.size()-1;
}
}
};</span>