首页 > 其他 > 详细

Sort Colors

时间:2014-07-16 17:18:18      阅读:392      评论:0      收藏:0      [点我收藏+]

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)时间,常数空间。

Sort Colors,布布扣,bubuko.com

Sort Colors

原文:http://blog.csdn.net/dutsoft/article/details/37832847

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!