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
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active"]
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; } } }
[/restab]
[/restabs]
6.Test
[restabs alignment="osc-tabs-right" responsive="true" icon="true" text="More" seltabcolor="#fdfdfd" seltabheadcolor="#000" tabheadcolor="blue"]
[restab title="Java" active="active" ]
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] + " "); } } }
[/restab]
[/restabs]
Comments | NOTHING