Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
解题思路:
1. 最开始做的是统计0,1,2的数目。然后要扫2遍
2. 这题只有3个数,想到可以用3个指针分别指向一个数字,2边的指针s, e分别指向0,和2。中间的指针 i扫描 s-e 数。碰到0,则swap( i, s),移动s . 碰到2, swap(i, e), 移动e.
第二个方法,注意移动i, s, e的移动。 由于等于2的时候, i 会和e 交换,也就是当i扫描到0的时候,i 交换的数一定为1,所以交换后,i也要移动。
Java Code:
public void sortColors(int[] A) {
int[] count = new int[3];
for (int i = 0; i < A.length; i++) {
switch (A[i]) {
case 0:
count[0]++;
continue;
case 1:
count[1]++;
continue;
case 2:
count[2]++;
continue;
}
}
for (int i = 0; i < A.length; i++) {
if (i < count[0]) {
A[i] = 0;
} else if (i < count[0] + count[1]) {
A[i] = 1;
} else {
A[i] = 2;
}
}
public void sortColors(int[] A) {
int s = 0;
int e = A.length - 1;
int i = s;
while (i <= e) {
if (A[i] == 0) {
A[i] = A[s];
A[s] = 0;
s++;
i++;
continue;
}
if (A[i] == 2) {
A[i] = A[e];
A[e] = 2;
e--;
continue;
}
i++;
}
}
No comments:
Post a Comment