您的位置:首页 > 其它

[leetcode] 75. Sort Colors

2016-08-15 11:08 381 查看
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.

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?

解法一:

没看follow up的时候,我觉得奇怪,这道题把0,1,2的个数分别数出来,赋值给nums就完了啊。

这里实现的类似冒泡算法。使用一个辅助变量,记录当前需要交换的位置。一次的rotate 0,1,2。不过不是one pass啊。

class Solution {
public:
void sortColors(vector<int>& nums) {
// rotate 0s
int idx = 0, tmp;
for(int i=0; i<nums.size(); i++){
if(nums[i]==0){
tmp = nums[i];
nums[i] = nums[idx];
nums[idx] = tmp;
++idx;
}
}
// rotate 1s
for(int i=idx; i<nums.size(); i++){
if(nums[i]==1){
tmp = nums[i];
nums[i] = nums[idx];
nums[idx] = tmp;
++idx;
}
}
// rotate 2s
for(int i=idx; i<nums.size(); i++){
if(nums[i]==2){
tmp = nums[i];
nums[i] = nums[idx];
nums[idx] = tmp;
++idx;
}
}
}
};

解法二:

使用两个idx,一个指向第一个不是0的位置,一个指向倒着看第一个不是2的位置。如果发现0,则交换至idx0指向的位置,idx0后裔以为;如果是2,交换至idx2指向的位置,idx2前移一位,i减1。循环至i==idx2。

class Solution {
public:
void sortColors(vector<int>& nums) {
int idx0 = 0, idx2 = nums.size()-1, tmp;
for(int i=0; i<=idx2; i++){
if(nums[i]==0){
swap(nums[i],nums[idx0++]);
}
else if(nums[i]==2){
swap(nums[i--],nums[idx2--]);
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode medium