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--;
            }
            
            
        }
    };



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

  • 相关阅读:
    读《被绑架的中国经济》有感
    互联网世界观
    了解360 ~~《我的互联网方法论》
    了解腾讯~~《马化腾的商业帝国》
    nginx 动静分离 以及 负载均衡配置
    linux 常用命令
    solr 配置中文分词器
    solr搜索配置权重
    JDK8集合类源码解析
    JDK8集合类源码解析
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656970.html
Copyright © 2011-2022 走看看