个人博客:https://luxialan.com

Sort Colors 分类: Leetcode 2015-01-18 09:30 76人阅读 评论(0) 收藏

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.

两种思路,一种遍历计数,一种三指针交换

class Solution {
public:
    void sortColors(int a[], int n) {
        int p,i,m;
        p=0,m=0;
        for(i=0;i<n;i++)
        {
            if(a[i]==0) p++;
            if(a[i]==1) m++;
        }
        for(i=0;i<p;i++)
        {
            a[i]=0;
        }
        for(;i<p+m;i++)
        {
            a[i]=1;
        }
        for(;i<n;i++)
        {
            a[i]=2;
        }
  }
};

class Solution {

public:

void sortColors(int a[], int n) {
        int i = -1;
        int j = -1;
        int k = -1;
        for(int p = 0; p < n; p ++)
        {
            if(a[p] == 0)
            {
                a[++k] = 2;   
                a[++j] = 1;    
                a[++i] = 0;   
            }
            else if(a[p] == 1)
            {
                a[++k] = 2;
                a[++j] = 1;
            }
            else
                a[++k] = 2;
        }

    }
};

class Solution {

public:
    void swap(int a[],int m,int n)
    {
        int tem=a[m];
        a[m]=a[n];
        a[n]=tem;
    }
    void sortColors(int a[], int n) {
        int l,cur,r;
        l=0,r=n-1,cur=n-1;
        while(cur>=l)
        {
            if(a[cur]==0)
            {
                swap(a,cur,l);
                l++;
            }
            else if(a[cur]==2)
            {
                swap(a,cur,r);
                r--;
                cur--;
            }
            else
            cur--;
        }
        
        
    }
};



版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-01-18 09:30  luxialan  阅读(106)  评论(0编辑  收藏  举报