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;
}
}
}
};
本文提供两种实现颜色排序的方法:一种使用双指针技术进行原地排序,适用于需要节省空间的场景;另一种采用计数排序思想,适合对稳定性有要求的应用。
1415

被折叠的 条评论
为什么被折叠?



