75. Sort Colors

Swap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public void sortColors(int[] nums) {
int orderedEndIndex = -1;

for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
swap(nums, i, ++orderedEndIndex);
}
}

for (int i = orderedEndIndex + 1; i < nums.length; i++) {
if (nums[i] == 1) {
swap(nums, i, ++orderedEndIndex);
}
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}

Swap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public void sortColors(int[] nums) {
int zeroEndIndex = 0, oneEndIndex = 0, twoEndIndex = 0;

for (int i = 0; i < nums.length; i++) {
if (nums[i] == 0) {
nums[twoEndIndex++] = 2;
nums[oneEndIndex++] = 1;
nums[zeroEndIndex++] = 0;
} else if (nums[i] == 1) {
nums[twoEndIndex++] = 2;
nums[oneEndIndex++] = 1;
} else {
// nums[i] == 2
nums[twoEndIndex++] = 2;
}
}
}
}

Swap

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public void sortColors(int[] nums) {
int zeroIndex = 0, twoIndex = nums.length - 1; // 下一个填入 0 的索引,下一个填入 2 的索引

int i = 0; // 原则:遍历到 1 时不处理,遍历到 0 时交换到左侧,遍历到 2 时交换到右侧
while (i <= twoIndex) { // 注意此处是小于等于 twoIndex,而不是小于 nums.length,否则会将右侧的 2 又交换回去
if (nums[i] == 0) {
swap(nums, i++, zeroIndex++); // 此处可以进行 i++ 操作是因为在遍历过程中 2 已经被交换至最右侧了,此时 i 左侧只可能为 0 或者 1
} else if (nums[i] == 2) {
// 交换至 nums[i] 的值可能为 0, 1, 2, 所以不推进 i 索引,而是要根据具体的值重新进入 while 循环继续处理
swap(nums, i, twoIndex--);
} else {
// nums[i] == 1
i++;
}
}
}

private void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}

References

75. Sort Colors