首页 > 代码库 > Sort Colors

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.

public class Solution {
    public void sortColors(int[] A) {
        int []count=new int[3];
        for(int i=0;i<count.length;i++)
            count[i]=0;
        for(int i=0;i<A.length;i++){
            count[A[i]]++;
        }
        for(int i=1;i<count.length;i++){
            count[i]=count[i]+count[i-1];
        }
        for(int i=0;i<A.length;i++){
            if(i<count[0]) A[i]=0;
            else if(i<count[1]) A[i]=1;
            else A[i]=2;
        }
    }
}
思路:计数排序,统计个数。O(n)时间,常数空间。