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

    做麻烦了,直接计数更快,只扫一遍。

    class Solution {
    public:
        void sortColors(int A[], int n) {
            int left = 0 ;
            int right = n-1;
            while(left < right)
            {
                while(A[left] == 0){
                    if(left == n-1)break;
                    left++;
                    }
                while(A[right] != 0){
                    if(right ==0)break;
                    right--;
                }
                if(left >= right)break;
                int temp = A[left];
                A[left] = A[right];
                A[right] = temp;
                left++;
                right--;
            }
            left =0;
            right = n-1;
            while(left < right)
            {
                while(A[left]!=2){
                    if(left == n-1)break;
                    left++;
                    }
                while(A[right]==2){
                    if(right ==0)break;
                    right--;
                    }
                if(left >= right)break;
                int temp = A[left];
                A[left] = A[right];
                A[right] = temp;
                left++;
                right--;
            }
        }
    };
    

      

     

  • 相关阅读:
    botzone Tetris2
    NOIP2017游记
    城乡联谊胡策会糊厕R3
    SRM 20
    AtCoder Regular Contest 082
    AtCoder Grand Contest 019
    复数模版
    SRM13
    NOI2017&&codeM2017游记
    java多线程编程
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3669606.html
Copyright © 2011-2022 走看看