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

      

     

  • 相关阅读:
    第三次上机
    第5次作业
    第二次上机练习
    第三次作业
    第一次作业
    第一次作业
    第二次上机练习
    第二次作业
    第一次作业
    第四周作业
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3669606.html
Copyright © 2011-2022 走看看