Sort Colors

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?

 
方法一:
统计0,1,2的个数,就可以计算出各自的下标,将0,1,2放入对应的位置。
C++实现代码如下:
#include<iostream>
using namespace std;

class Solution {
public:
    void sortColors(int A[], int n) {
        int count0,count1,count2;
        count0=count1=count2=0;
        int i;
        for(i=0;i<n;i++)
        {
            if(A[i]==0)
                count0++;
            else if(A[i]==1)
                count1++;
            else
                count2++;
        }
        i=0;
        int j=count0;
        int k=count0+count1;
        while(i<count0)
        {
            if(A[i]==0)
                i++;
            else if(A[i]==1)
            {
                swap(&A[i],&A[j]);
                j++;
            }
            else if(A[i]==2)
            {
                swap(&A[i],&A[k]);
                k++;
            }
        }
        while(j<count0+count1)
        {
            if(A[j]==1)
                j++;
            else if(A[j]==2)
            {
                swap(&A[j],&A[k]);
                k++;
            }
        }
    }
    void swap(int *a,int *b)
    {
        int temp=*a;
        *a=*b;
        *b=temp;
    }
};

int main()
{
    Solution s;
    int arr[10]={0,1,2,2,1,1,0,2,0,2};
    s.sortColors(arr,10);
    for(auto a:arr)
        cout<<a<<" ";
    cout<<endl;
}

方法二:使用快速排序的分割方法。使用i,j,k三个下标,i始终指向的是第一个1,而j始终执行的是最后一个2的前一个位置。k用来遍历整个数组。

C++实现代码:

#include<iostream>
using namespace std;

class Solution {
public:
    void sortColors(int A[], int n) {
        if(n==0)
            return;
        int i=0;
        int k=0;
        int j=n-1;
        while(k<=j)
        {
            if(A[k]==0)
            {
                swap(&A[k],&A[i]);
                k++;
                i++;
                continue;
            }
            if(A[k]==2)
            {
                swap(&A[k],&A[j]);
                j--;
                continue;
            }
            k++;
        }
    }
    void swap(int *a,int *b)
    {
        int temp=*a;
        *a=*b;
        *b=temp;
    }
};

int main()
{
    Solution s;
    int arr[11]={0,1,2,2,1,1,0,2,0,2,2};
    s.sortColors(arr,1);
    for(auto a:arr)
        cout<<a<<" ";
    cout<<endl;
}

 

posted @ 2014-11-19 15:23  Jessica程序猿  阅读(159)  评论(0编辑  收藏  举报