Sort Colors II
Given colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4].Basic Idea:
3 2 2 1 4 2 2 -1 1 4 2 -1 -1 1 4 0 -2 -1 1 4 -1 -2 -1 0 4 -1 -2 -1 -1 0
Given colors=[3, 2, 2, 1, 4], k=4, your code should sort colors in-place to [1, 2, 2, 3, 4]. 3 2 2 1 4
2 2 -1 1 4
2 -1 -1 1 4
0 -2 -1 1 4
-1 -2 -1 0 4
-1 -2 -1 -1 0 class Solution {
/**
* @param colors: A list of integer
* @param k: An integer
* @return: nothing
*/
public void sortColors2(int[] colors, int k) {
int i = 0;
while (i < colors.length) {
if (colors[i] > 0) {
// 说明需要处理colors[i]存放的颜色
int color = colors[i];
if (colors[color - 1] > 0) {
// 当color对应index存有其他颜色时
colors[i] = colors[color - 1]; // 把color对应index的颜色存入i
colors[color - 1] = -1; // 把对应index存放其index颜色的数量的相反数
} else {
// 当对应index已经是计数器时
colors[i] = 0; // 表示原来这里的颜色已经存储过
colors[color - 1]--;
i++; // 考虑右边的元素
}
} else {
// 当前i位置已经处理过
i++;
}
}
// 从右往左,把排序后的数组复原在原来位置
int j = colors.length - 1;
for (i = colors.length - 1; i >= 0; i--) {
int count = -colors[i];
if (count == 0) continue;
while (count > 0) {
colors[j--] = i + 1;
count--;
}
}
}
}