有一個(gè)只由0谋作,1,2三種元素構(gòu)成的整數(shù)數(shù)組乎芳,請使用交換遵蚜、原地排序而不是使用計(jì)數(shù)進(jìn)行排序帖池。
給定一個(gè)只含0,1吭净,2的整數(shù)數(shù)組A及它的大小碘裕,請返回排序后的數(shù)組。保證數(shù)組大小小于等于500攒钳。
測試樣例:
輸入:[0,1,1,0,2,2],6
返回:[0,0,1,1,2,2]
class ThreeColor {
public:
void swap(vector<int> &A, int i, int j)
{
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
const static int first = 0, mid = 1, last = 2;
vector<int> sortThreeColor(vector<int> A, int n) {
// write code here
int cmp_val = 1;
int p_first = 0;
int p_last = n-1;
int p_curr = 0;
for(int i=0; i<n; i++){
switch(A[p_curr])
{
case first:
swap(A, p_curr++, p_first++);
break;
case mid:
++p_curr;
break;
case last:
swap(A, p_curr, p_last--);
break;
default:
break;
}
}
return A;
}
};