本文共 930 字,大约阅读时间需要 3 分钟。
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 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; } } }};
转载地址:http://aqxti.baihongyu.com/