一.问题描述
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.
二.我的解题思路
这道题挺特殊的,我采用的是很简单的解法。先遍历整个vector,得到0,1,2的个数,然后再遍历一次进行赋值即可。这种做法的时间复杂度是O(n),但是需要遍历整个数组两次才行。测试通过的程序如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int len = nums.size();
int num0,num1,num2; num0=num1=num2=0;
for(int i=0;i<len;i++){
if(nums[i]==0) num0++;
if(nums[i]==1) num1++;
if(nums[i]==2) num2++;
}
int idx[3]={0,num0,num0+num1};
for(int i=0;i<len;i++){
if(i<num0) nums[i]=0;
if(i>=num0 && i<(num0+num1)) nums[i]=1;
if(i>=(num0+num1)) nums[i]=2;
}
}
};后来又在网上看到别人比较牛逼的思路:
class Solution {
public:
void sortColors(vector<int>& A) {
int len = A.size();
int i = -1;
int j = -1;
int k = -1;
for (int p = 0; p < len; p++)
{
//根据第i个数字,挪动0~i-1串。
if (A[p] == 0)
{
A[++k] = 2; //2往后挪
A[++j] = 1; //1往后挪
A[++i] = 0; //0往后挪
}
else if (A[p] == 1)
{
A[++k] = 2;
A[++j] = 1;
}
else
A[++k] = 2;
}
}
};这种思路是判断0,1,2需要往后挪动的次数,只需要遍历整个数组一次即可。
三色排序算法解析
本文介绍了一种特殊的三色排序问题,即给定一个包含红色、白色和蓝色对象的数组,要求将相同颜色的对象相邻排列,并按红白蓝顺序输出。提供两种解决方案,一种为两遍扫描法,时间复杂度O(n),另一种为单遍扫描法,仅需遍历数组一次。
341

被折叠的 条评论
为什么被折叠?



