zoukankan      html  css  js  c++  java
  • [LeetCode] 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?

    class Solution {
    public:
        void sortColors(int A[], int n) {
            int num0 = count(A,A+n,0);
            int num1= count(A,A+n,1);
            int num2 = count(A,A+n,2);
            int i = 0;
            while(i<num0)
            {
                A[i++] = 0;
            }
            while(i<num0+num1)
            {
                A[i++] = 1;
                
            }
            while(i<n)
            {
                A[i++] = 2;
            }
        }
    };

    遍历一遍的方法如下:
    遍历一遍把遇到0都放到左边,把遇到的2都放到右边。

    class Solution {
    public:
       void sortColors(int A[], int n) {
            int i = 0,f = 0;
            int j = n-1;
          while(i!=j && f<n)
          {
            while(f<n && A[f]==1)
            {
               f++;
            }
            if(f>j)
                break;
            if(f<n && A[f]==0)
            {
               if(f==i)
               {
                   i++;
                   f++;
                   continue;
               }
               A[f]=A[i];
               A[i++] = 0;
            }
            else if(f<n && A[f]==2)
            {
                if(j==f)
                {
                    j--;
                    f++;
                    continue;
                }
                A[f] = A[j];
                A[j--] = 2;
                if(f>j)
                 break;
            }
            
                
            
          }//end while
            
        }
    };
  • 相关阅读:
    JAVA 大数据基本操作
    C++ set 基本操作
    JVM 线上故障排查基本操作
    Git基本常用命令
    Git 入门:概念、原理、使用
    30分钟学会如何使用Shiro
    做个男人,做个成熟的男人,做个有城府的男人
    Nginx的最基本功能以及简单配置
    博客网站
    单点登录原理与简单实现
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3843715.html
Copyright © 2011-2022 走看看