您的位置:首页 > 其它

[LeetCode] Sort Colors

2015-11-29 16:48 363 查看
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.

click to show follow up.

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?

思路:

题目意思就是给你一个元素取值有限的数组,让你排序,直接想到的是计数排序,但是需要遍历两边,问你有没有只遍历一遍的方法。

我没想出来,看了别人用交换元素的方法,觉得有趣,就自己写了下,比他简略一点。

class Solution {
public:
void sortColors(vector<int>& nums) {
auto start = nums.begin()-1;
auto end = nums.end();
auto p = nums.begin();
while( p!=end ){
if(*p==0){
swap(++start,p);
p++;
}
else if(*p==2){
swap(--end,p);
}
else
p++;
}
}
private:
void swap(vector<int>::iterator a, vector<int>::iterator b)
{
int c = *a;
*a = *b;
*b = c;
}
};


下面是计数的方法:

class Solution {
public:
void sortColors(vector<int>& nums) {
auto p = nums.begin();
int x=0,y=0,z=0;
while( p!=nums.end() )
{
*p==0?x++:(*p==1?y++:(*p==2?z++:0));
p++;
}
for(int i=0;i<nums.size();i++)
{
i<x?nums[i]=0:(i<x+y?nums[i]=1:nums[i]=2);
}
}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode