One pointer. Two pass. Just be careful:

  1. for loop: i is on color genre, not nums.length;
  2. self-increment each time: count++ is independent of i, j.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    public 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public void sortColors(int[] nums) {
int red = 0, blue = nums.length - 1;
for (int i = 0; i <= blue; ++i) {
if (nums[i] == 0) {
int tmp = nums[red];
nums[red] = nums[i];
nums[i] = tmp;
red++;
}
else if (nums[i] == 2) {
int tmp = nums[blue];
nums[blue] = nums[i];
nums[i] = tmp;
i--;
blue--;
}

}
}
}
  1. blue:2, 交换完成之后i--, 因为要继续检查被2交换回来的数;
  2. red:0, 没有i++, 不用检查和0交换的数,因为肯定是1;
  3. 上面的,为什么“和0交换的一定是1?” 因为如果是2,直接进去后面一个if了,进去的结果是2会被都移动到最后面,所以从0左边开始碰到的肯定都是1,而1不用做任何处理