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.
这个其实就是荷兰国旗问题。这种问题的关键是保持两个指针,把数组分为前中后三个部分,前,后两部分分别是红色和蓝色,中间是杂色。然后遍历一遍,把杂色区域中的红色和蓝色交换出去。
我写了一个无比累赘但是十分容易理解的代码,Accept了
void swap(int * a, int * b){
int tmp=*a;
*a=*b;
*b=tmp;
}
void sortColors(int A[], int n) {
int r=0;
int w=0;
int b=n-1;
while(A[r]==0){
r++;
w++;
}
while(A[b]==2){
b--;
}
while(w<=b && r<=b){
if(A[w]==0){
swap(A+r,A+w);
r++;
if(r>w)
w=r;
}
if(A[w]==2){
swap(A+b,A+w);
b--;
}
while(A[w]==1) w++;
while(A[r]==0){
r++;
if(r>w)
w=r;
}
while(A[b]==2) b--;
}
}
本文提供了一种解决荷兰国旗问题的代码实现,通过使用两个指针将数组分为三部分,实现不同颜色的元素相邻排列。
398

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



