Leetcode 75. Sort Colors

来源:互联网 发布:紫色水离子淘宝店地址 编辑:程序博客网 时间:2024/06/05 21:01

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?

s思路:
1. 复习一下排序,如果用来排序的对象都来自已知的有限尺寸的集合。这就用counting sort,复杂度为o(n)。但需要two-pass
2. 这道题,就3个对象的集合排序,对象更少,用counting sort肯定是可以的,但仍然需要two-pass,有点大材小用。
3. 仔细观察排好序的vector,如下:
这里写图片描述
三个元素排序,结果就是需要确定两个边界:left,right。所以,应该可以用two-pointer来实现,只需要one-pass即可!
4. 具体思路:left指向1的最左边,right指向1的最右边,即:遍历nums时,如果nums[i]==0,则swap(nums[i],nums[left++]),这里特别注意,交换后,还需要继续判断是否nums[i]==0,所以用while来做这个多次的判断;如果nums[i]==2,则swap(nums[i],nums[right–]).
5.

//方法1:two pointerclass Solution {public:    void sortColors(vector<int>& nums) {        //        int n=nums.size();        int left=0,right=n-1;        for(int i=0;i<=right;i++){            while(i<=right&&nums[i]==2){                nums[i]=nums[right];                nums[right--]=2;                }                while(i>=left&&nums[i]==0){                nums[i]=nums[left];                nums[left++]=0;               }        }    }};//方法2:counting sortclass Solution {public:    void sortColors(vector<int>& nums) {        //        int n=nums.size();        int zero=0,one=0,two=0;        for(int i:nums){            if(i==0) zero++;            else if(i==1) one++;            else if(i==2) two++;        }        for(int i=0;i<n;i++){            if(zero>0) {nums[i]=0; zero--;}            else if (one>0) {nums[i]=1; one--;}             else {nums[i]=2;}        }               }};
0 0
原创粉丝点击