sort colors


Sort Colors
计数排序,计算每种color的个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void (int[] nums) {
int[] colors = new int[3];
for (int i : nums) {
colors[i]++;
}
int index = 0;
int color = 0;
for (int i : colors) {
while (i-- > 0) {
nums[index++] = color;
}
++color;
}
}

可以用双指针的方法去做,把 0 全部交换到左边, 2 全部交换到右边。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void (int[] nums) {
if (nums == null || nums.length == 0)
return;
int left = 0, right = nums.length - 1;
for (int i = 0; i <= right;) {
if (nums[i] == 2) {
swap(nums, i, right);
--right;
} else if (nums[i] == 0) {
swap(nums, i, left);
++left;
++i;
} else
++i;
}
}

public void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}