Sort Colors

来源:互联网 发布:炉石大数据各数据意义 编辑:程序博客网 时间:2024/06/05 16:27

题目描述:
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?

分析:
因为题目要求只能扫一次,所以用a,b,c分别记录当前0,1,2排序后的最后一位得下标,如a表示最后一个0的下标,不断更新即可。

代码如下:

 void sortColors(vector<int>& num) {        int len=num.size();       int a=0,b=0,c=0;        for(int i=0;i<len;i++){            if(num[i]==0){            num[c++]=2;            num[b++]=1;            num[a++]=0;            }            else if(num[i]==1){            num[c++]=2;            num[b++]=1;            }            else if(num[i]==2){            num[c++]=2;            }        }    }
原创粉丝点击