题目:
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.
题意:
给一个数组,里面的数字是0,1,2,对该数组进行排序。
思路:
这个数组的特征明显,只包含三个数字,对该数组进行排序最简单直观的方法是先扫描一遍数组,统计0,1,2的个数。然后第二次扫描改变数组的元素。
代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int size = nums.size();
if(size == 0)return;
int zeros = 0,ones = 0,twos = 0;
for(int i = 0; i < size; i++){
switch(nums[i]){
case 0:{
zeros++;
break;
}
case 1:{
ones++;
break;
}
case 2:{
twos++;
break;
}
}
}
for(int i = 0; i < zeros; i++)
nums[i] = 0;
int total_zeros_ones = zeros + ones;
for(int i = zeros; i < total_zeros_ones; i++)
nums[i] = 1;
for(int i = total_zeros_ones; i < size; i++)
nums[i] = 2;
}
};
然而上面的方法需要扫面数组两次,以下的方法只需要扫描数组一次。只需要保留三个指针,第一个指针指向最前面所有0的下一个非0处,第三个指针指向数组最后面的所有2的下一个非2处,第二个指针是扫描指针,从第一个指针往后倒第三个指针间进行扫描。如果遇到0就与前面的指向0的指针的数值进行互换,如果是2就与第三个指针互换,并且移动指针。但是需要考虑比如第二个指针与第一个指针互换后,第一个指针原来指的数字可能是2,所以此时不能直接移动第二个指针往后,需要继续判断,如果第二个指针是1那么往后毋庸置疑,否则需要继续判断。代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int size = nums.size();
if(size == 0)return;
int first = 0,second = 0,third = size - 1;
while(first < size && nums[first] == 0)first++;
while(third >= 0 && nums[third] == 2)third--;
if(first == size || third == -1)return;
second = first;
while(second <= third){
switch(nums[second]){
case 0 :{
int temp = nums[second];
nums[second] = nums[first];
nums[first] = temp;
first++;
second = (first > second)?first:second;
break;
}
case 1: {
second++;
break;
}
case 2:{
int temp = nums[second];
nums[second] = nums[third];
nums[third] = temp;
third--;
break;
}
}
}
}
};