您的位置:首页 > 其它

75. Sort Colors

2017-07-07 11:00 288 查看
题目

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?

分析
由于待排序数字较少,可以使用计数排序,但这需要遍历两次数组,如果要遍历一次,可以参考Sharing C++ solution with Good Explanation博文,利用low,mid,high记录0,1,2的位置,其中low指向最后一个0放置的位置,high指向第一个2放置的位置,mid指向最后一个1放置的位置,遍历数组时,根据mid指向的值分别考虑0,1,2三种情况,其中遇到0时交换low和mid,并且各自向后移动一个位置,遇到1时只有mid向后移,遇到2时交换mid和high,同时high向前移,mid保持不动,综上,当交换2后,交换到前面的值可能是0或1,所以需要mid保持不动再次进行考虑,但遇到0时,由于mid初始与low处于同一位置,因此遇到0时交换来的只能是1,所以都向后移动。

计数排序代码如下:

class Solution {
public:
void sortColors(vector<int>& nums) {
vector<int> cnt(3,0);
for(int i=0;i<nums.size();++i){
cnt[nums[i]]++;
}
vector<int>::iterator it=nums.end()-1;
for(int i=2;i>-1;--i){
while(cnt[i]!=0){
*it=i;
--it;
cnt[i]--;
}
}
return ;
}
};只遍历一次代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
int low=0,mid=0,high=nums.size()-1;
while(mid<=high){
if(nums[mid]==0){
int temp=nums[low];
nums[low++]=nums[mid];
nums[mid++]=temp;
}
else if(nums[mid]==1){
mid++;
}
else if(nums[mid]==2){
int temp=nums[high];
nums[high--]=nums[mid];
nums[mid]=temp;
}
}
return ;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: