zoukankan      html  css  js  c++  java
  • 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--;
            }
            
            
        }
    };



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

  • 相关阅读:
    Linux iptables常用命令
    Docker数据卷
    Ubuntu14.04下安装docker 1.9
    初识微服务
    初识微服务
    无状态服务(stateless service)
    git生成ssh key 避免每次push都要输入账号密码
    fiddler和xampp安装成功后,网站打不开的原因
    ajax设置自定义请求头信息
    ajax跨域之设置Access-Control-Allow-Origin
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656970.html
Copyright © 2011-2022 走看看