您的位置:首页 > 编程语言 > C语言/C++

【LeetCode从零单刷】Sort Colors

2015-09-21 19:38 387 查看
题目:
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.

解答:
说是全局排序,但其实同一种颜色内部,根本无所谓顺序都是相同的。所以,所需要知道的只是每种颜色最开始出现的位置。

class Solution {
public:
void sortColors(vector<int>& nums) {
int len = nums.size();
int a = 0, b = 0, c = 0;
for(int i=0; i<len; i++)
{
if(nums[i] == 0) a++;
if(nums[i] == 1) b++;
if(nums[i] == 2) c++;
}

nums.clear();
for(int i=0; i<len; i++)
{
if(i < a)           nums.push_back(0);
else if(i < (a+b))  nums.push_back(1);
else nums.push_back(2);
}
}
};


但是这道题并没有结束,还有更多的要求:

Follow up:

A rather straight forward solution is a two-pass algorithm using counting sort.

First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

Could you come up with an one-pass algorithm using only constant space?

当只能遍历一次数组的时候呢?有两个思路:

类似快排思想,设置两个游标:start 和 end,比1小的放到 start 位置,比1大的放到 end 位置,然后逐渐往中间靠拢;
设置三个游标,分别标记0,1,2的开始位置。与以上方法不同的是,边移动边赋值,这样会导致一个问题:新老值的赋值顺序
这里有篇博客贴出了代码:http://www.cnblogs.com/ganganloveu/p/3703746.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode