`

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.

解决这道题目我们可以采用计数排序算法。首先我们遍历数组得到每个颜色的个数,记录到计数数组count[i]中;接下来我们累加计数数组,使count[i] = count[i] + count[i - 1],这样其实就是给不同的元素给定了不同大小的空间;然后我们遍历需要排序的数组,用一个临时数组tem[]记录遍历过的元素,使tem[--count[nums[i]]] = nums[i];这样相当于将每种颜色从它所属的空间后面开始填充,直到结束。代码如下:
public class Solution {
    public void sortColors(int[] nums) {
        if(nums == null || nums.length == 0)
            return ;
        int[] count = new int[3];
        int[] tem = new int[nums.length];
        for(int i = 0; i < nums.length; i++) 
            count[nums[i]] ++;
        for(int i = 1; i < 3; i++)
            count[i] = count[i] + count[i - 1];
        for(int i = 0; i < nums.length; i++) 
            tem[--count[nums[i]]] = nums[i];
        System.arraycopy(tem, 0, nums, 0, tem.length);
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics