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.
这道题目刚看的时候第一个想法是排序算法,尤其结合快排的思想很容易想到以下的算法:从左边循环找2放到队尾,从右边循环找0放到队首。代码:
class Solution {
public:
void sortColors(int A[], int n) {
int second=n-1, zero=0;
for (int i=0; i<=second; i++) {
while (A[i]==2 && i<second) swap(A[i], A[second--]);
while (A[i]==0 && i>zero) swap(A[i], A[zero++]);
}
}
};
算法复杂度n*n,但是仔细想想,由于数组中只有三种变量0,1,2,所以,如果用标记位可以减少算法复杂度,通过三个标记为记录三种变量最后一位所在的位置:
代码:
class Solution {
public:
//use counting sort
void sortColors(int A[], int n) {
int red = -1, white = -1, blue = -1;
for(int i = 0; i < n; i++){
if(A[i] == 0){
A[++blue] = 2;
A[++white] = 1;
A[++red] = 0;
}
else if(A[i] == 1){
A[++blue] = 2;
A[++white] = 1;
}
else if(A[i] == 2)
A[++blue] = 2;
}
}
};