顿搜
飞过闲红千叶,夕岸在哪
类目归类
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.
Input:0, 1, 0, 2, 0, 2
Ouput: 0, 0, 0, 1, 2, 2
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 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] + " ");
}
}
}