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.
Have you met this question in a real interview?
思路: 把每个颜色有多少个存储在一个数组里, 然后从头到尾 添加颜色。
易错点: index 别忘了 加加。
public class Solution {
public void sortColors(int[] A) {
int[] colors = new int[3];
for(int i : A){
colors[i]++;
}
int index = 0;
for(int i = 0; i < 3; i++){
while(colors[i] > 0){
A[index] = i;
colors[i]--;
index++;//--
}
}
}
}