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

  

 

原文地址:https://www.cnblogs.com/pengyu2003/p/3669606.html