您的位置:首页 > 其它

Leetcode: Sort Colors

2013-10-28 12:56 288 查看
http://oj.leetcode.com/problems/sort-colors/

// The easy way is to use count sort, but it is going to need two-pass
// The solution below need one-pass.
// The idea is to keep all the numbers before index0 are 0, and all the numbers after index2 are 2.
// One thing important is that, we should swap elements, instead of updating the array directly.
class Solution {
private:
void swap(int &a, int &b){
int tmp=a;
a=b;
b=tmp;
}
public:
void sortColors(int A[], int n) {
int index0=0, index2=n-1;
int current=0;
while(current<=index2){
if(A[current]==0) swap(A[index0++],A[current]);
else if(A[current]==2) swap(A[index2--],A[current]);
else current++;
current=max(current,index0);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: