您的位置:首页 > 其它

[LeetCode]Sort Colors

2013-06-01 09:45 183 查看
class Solution {
//reverse travel the array
//endOfZero + endOfOne
//classified discuss for current number{0, 1, 2}
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int e0, e1;
e0 = e1 = n-1;
for (int cur = n-1; cur >= 0; --cur)
{
if(A[cur] == 1)
swap(A[e0--], A[cur]);
else if (A[cur] == 2)
{
swap(A[e0], A[cur]);
swap(A[e0], A[e1]);
e0--;
e1--;
}
}
}
};

second time

class Solution {
public:
void sortColors(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> cntSort(3, 0);
for(int i = 0; i < n; ++i) cntSort[A[i]]++;

int k = 0;
for(int i = 0; i < 3; ++i)
{
int curCnt = cntSort[i];
for(int j = 0; j < curCnt; ++j)
{
A[k++] = i;
}
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: