[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
        
    }
};
原文地址:https://www.cnblogs.com/Xylophone/p/3843715.html