[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; } } } };
相关文章推荐
- Sort Colors —LeetCode
- [LeetCode]98. SortColors颜色排序
- Leetcode:Sort Colors
- [leetcode 75] Sort Colors-----------只有三种颜色的排序
- [LeetCode] 75. Sort Colors
- LeetCode-Sort Colors
- Leetcode(Sort Colors )
- LeetCode75 Sort Colors
- 【LeetCode】 075. Sort Colors
- leetcode:Sort Colors
- [leetcode]Sort Colors
- Sort Colors 分类: Leetcode 2015-01-18 09:30 76人阅读 评论(0) 收藏
- 【C++】【LeetCode】75. Sort Colors
- Leetcode 75 Sort Colors
- Leetcode: Sort Colors
- 【Leetcode】Sort Colors in JAVA
- leetcode-java-75. Sort Colors
- [Leetcode] Sort Colors
- 【一天一道LeetCode】#75. Sort Colors
- leetCode(30):Sort Colors