码迷,mamicode.com
首页 > 其他好文 > 详细

Sort Colors

时间:2014-07-16 17:18:44      阅读:207      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!