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.
本题为经典的荷兰国旗问题,当我们将红白蓝三色想象成条状物,有序排序后正好是荷兰国旗。解决这个问题,类似于快排中的partion过程,不过这里需要三个指针:begin, current, end. begin与current初始化为数组首部,end为数组尾部。具体算法如下:
1. cur=1时, cur++;
2. cur=0时, cur与begin交换值,并且cur++, begin++;这种情况下,cur与begin的值有两种情况,(1) cur与begin都为0;(2) cur为0,begin为1;
3. cur=2时, cur与end交换值,此时cur不变,end--;
具体代码如下:
class Solution {
public:
void sortColors(int A[], int n) {
int begin=0, cur=0,end=n-1;
while(cur<=end)
{
if(A[cur]==1) cur++;
else if(A[cur]==0)
{
swap(A[cur],A[begin]);
cur++;
begin++;
}
else
{
swap(A[cur],A[end]);
end--;
}
}
}
void swap(int &a, int &b)
{
int tmp=a;
a=b;
b=tmp;
}
};