[leetcode] 75. Sort Colors

来源:互联网 发布:ubuntu 压缩 编辑:程序博客网 时间:2024/06/13 05:26

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--]);            }        }    }};


0 0
原创粉丝点击