One pointer. Two pass. Just be careful:
- for loop:
i
is on color genre, notnums.length
; - self-increment each time:
count++
is independent ofi, j
.1
2
3
4
5
6
7
8
9public void sortColors(int[] nums) {
int[] colors = new int[3];
for (int num : nums) colors[num]++;
for (int i = 0, count = 0; i < 3; ++i) {
for (int j = 0; j < colors[i]; ++j) {
nums[count++] = i;
}
}
}
Two pointers. Iterate through; swap red pointer number with current 0, swap blue pointer number with current 2.
attention: for ... i <= blue
1 | class Solution { |
- blue:2, 交换完成之后
i--
, 因为要继续检查被2交换回来的数; - red:0, 没有
i++
, 不用检查和0交换的数,因为肯定是1; - 上面的,为什么“和0交换的一定是1?” 因为如果是2,直接进去后面一个if了,进去的结果是2会被都移动到最后面,所以从0左边开始碰到的肯定都是1,而1不用做任何处理