TypechoJoeTheme

IT技术分享

统计

[LeetCode 75] Sort Colors [Java] [Runtime : 0MS]

2017-08-31
/
0 评论
/
637 阅读
/
正在检测是否收录...
08/31

1. Description

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.

2. Runtime Distribution

3. Submission Details

4. Example

Input:0, 1, 0, 2, 0, 2
Ouput: 0, 0, 0, 1, 2, 2

5. Code

public void sortColors(int[] nums) {
    if (nums == null || nums.length == 0) {
        return;
    }
    int[] bucket = new int[3];
    for (int i = 0; i < nums.length; i++) {
        bucket[nums[i]]++;
    }
    int count = 0;
    for (int i = 0; i < bucket.length; i++) {
        while (bucket[i]-- > 0) {
            nums[count++] = i;
        }
    }
}

6.Test

public class LeetCode0075 {
    public void sortColors(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int[] bucket = new int[3];
        for (int i = 0; i < nums.length; i++) {
            bucket[nums[i]]++;
        }
        int count = 0;
        for (int i = 0; i < bucket.length; i++) {
            while (bucket[i]-- > 0) {
                nums[count++] = i;
            }
        }
    }

    public static void main(String[] args) {
        int[] nums = { 0, 1, 0, 2, 0, 2 };
        LeetCode0075 leetcode = new LeetCode0075();
        leetcode.sortColors(nums);

        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }
}
Sort
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/744/(转载时请注明本文出处及文章链接)