Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
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.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
two-pass 的方法比较容易想,自己尝试了一下one pass的,竟然ac了。先把思路写下来,有更好方法再来update
思路:
使用4个指针,两个指针分别从前和后寻找 为0的值,如果后面有为0的值,则往前放
另外两个指针分别从前和后寻找 为2的值,如果前面有为2的值,则往前放
把0,和2 都放到了最前面和最后面,则中间剩下的,就是1了。
public class Solution {
public void sortColors(int[] A) {
int i0left = 0;
int i0right = A.length - 1;
int i2left = 0;
int i2right = A.length - 1;
for (int i = 0; i < A.length; i++) {
if (i0left < i0right){
//如果为0,则继续往后找
if (A[i0left] == 0) {
i0left++;
} else {
//如果左边的值不为0,但是它的右边还有为0的值,则交换
if (A[i0right] == 0) {
A[i0right] = A[i0left];
A[i0left] = 0;
}
i0right--;
}
}
if (i2left < i2right){
if (A[i2right] == 2) {
i2right--;
} else {
if (A[i2left] == 2) {
A[i2left] = A[i2right];
A[i2right] = 2;
}
i2left++;
}
}
}
}
}
344

被折叠的 条评论
为什么被折叠?



