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



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

  • 相关阅读:
    HTTPs与HTTP的区别&HTTPs如何建立连接
    HTTP协议常见状态码和字段
    服务器负载均衡
    ARP协议工作原理
    C++智能指针
    C++类型转换
    Rust 只出现一次的数字 两种解法
    Rust 存在重复元素 两种解法
    Rust 旋转数组
    Rust 动态规划 买卖股票的最佳时机 II
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656970.html
Copyright © 2011-2022 走看看