Sort Colors

来源:互联网 发布:centos在线安装jdk1.7 编辑:程序博客网 时间:2024/05/20 15:11

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?


第一种做法是先扫一遍rgb的颜色个数, 然后依次赋值。

class Solution {public:    void sortColors(int A[], int n) {        int r=0,g=0,b=0;        for(int i=0; i<n; i++){            if (A[i]==0) r++;            if (A[i]==1) g++;            if (A[i]==2) b++;        }        for (int i=0; i<r;i++){            A[i]=0;        }        for (int i=r;i<r+g;i++)            A[i]=1;        for (int i=r+g; i<n;i++)            A[i]=2;    }};

第二种做法就是维护两个指针。用counting sort的思想。就是加入只有0和1,那么我们需要一个last+1of 0来计数,每次遇到0,就把他swap一下,到最后就是以last+1为边界,两边是0和1,现在多了一个2,那么同样维护一个0的计数,多维护一个2的计数,遇到0换到0那边,遇到2换到2那边,注意换到2的时候,index不更新,因为需要再判断一次是0还是2,直到2的首位为止。。

class Solution {public:    void sortColors(int A[], int n) {        int i=0, s0=0,s2=n-1;        while(i<=s2){            if (A[i]==0)                swap(A[s0++],A[i++]);            else if (A[i]==2)                swap(A[s2--],A[i]);            else                i++;        }    }};


0 0
原创粉丝点击