问题:Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
荷兰国旗问题。可以使用三路快排的分治思想,同样的也可以用计数排序的思想。
class Solution {
public void sortColors(int[] nums) {
// O(N) count 0s, 1s, 2s and overwrite array
int one = 0;
int two = 0;
int zero = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 1){
one++;
}else if (nums[i] == 2){
two++;
}else if(nums[i] == 0){
zero++;
}
}
// overwrite array
int index = 0;
while(zero > 0){
nums[index] = 0;
index++;
zero--;
}
while(one > 0){
nums[index] = 1;
index++;
one--;
}
while(two > 0){
nums[index] = 2;
index++;
two--;
}
}
}