题目虽然简单, 但是确实找了好一会的bug,对着数据- -
这题值得再写一遍。
class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(n <= 0)
return ;
int p0 = -1;
while(p0 + 1 < n)
if(A[p0 + 1] == 0)
++ p0;
else
break;
if(p0 == n - 1)
return ;
int p2 = n;
while(p2 - 1 >= 0)
if(A[p2 - 1] == 2)
-- p2;
else
break;
if(p0 + 1 == p2)
return ;
int p1 = p0 + 1;
while(p1 < p2){
if(A[p1] == 2){
swap(A[p1], A[p2 - 1]);
-- p2;
while(p2 - 1 >= 0)
if(A[p2 - 1] == 2)
-- p2;
else
break;
}
if(A[p1] == 0){
swap(A[p1], A[p0 + 1]);
++ p0;
++ p1;
}else ++ p1;
}
}
};