12.24 2014
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.
class Solution {
public:
void sortColors(int A[], int n) {
int red=0;
int blue=n-1;
int i=0;
while(i<blue+1){
if(A[i]==0){
swap(A[i],A[red]);
red++;
i++;
}
else if(A[i]==2){
swap(A[i],A[blue]);
blue--;
}
else
i++;
}
}
};
总结:
1. 思路:使用两个指针记录下一个红色和蓝色放的位置,红色起始位置为0,蓝色的为最后一位。当遇到是红色,则交换当前值,把他放到更靠近左边的位置,并更新red的index,和将考察element移到下一个;如果遇到蓝色,则交换当前值,但是由于不知道当前值是什么,所以只更新下一个蓝色该放得位置,但要继续考察被交换以后的当前index对应的值。若遇到白色,只是单纯的考察下一个element。
2. 该方法无法推广到多种颜色。