leetcode 75. Sort Colors
来源:互联网 发布:淘宝卖假酒怎么处罚 编辑:程序博客网 时间:2024/06/09 21:25
三值排序问题:用三个指针跟踪
top_bottom:第三个分区的下界,这个指针往后都是第三个分区的值;
bottom_top:第一个分区的上界,这个指针往前都是第一个分区的值,这个指针和middle_top之间的都是第二个分区的值;
middle_top:第二个分区的上界,这个指针和top_bottom之间的元素都是待排序的。
思路挺像快排的。
class Solution {public: void sortColors(vector<int>& nums) { int top_bottom = int(nums.size()), bottom_top = -1, middle_top = 0, temp = 0; while (middle_top < top_bottom) { cout << middle_top << " " << top_bottom << endl; if (nums[middle_top] == 0 && middle_top > bottom_top) { temp = nums[bottom_top + 1]; nums[bottom_top + 1] = nums[middle_top]; nums[middle_top] = temp; bottom_top++; } else if (nums[middle_top] == 2 && middle_top < top_bottom) { temp = nums[top_bottom - 1]; nums[top_bottom - 1] = nums[middle_top]; nums[middle_top] = temp; top_bottom--; } else { middle_top++; } } }};
算法在wiki上写得很清楚,https://en.wikipedia.org/wiki/Dutch_national_flag_problem#Pseudocode
而且上面的伪代码比这里实现的好。
procedure three-way-partition(A : array of values, mid : value): i ← 0 j ← 0 n ← size of A - 1 while j ≤ n: if A[j] < mid: swap A[i] and A[j] i ← i + 1 j ← j + 1 else if A[j] > mid: swap A[j] and A[n] n ← n - 1 else: j ← j + 1
0 0
- [LeetCode]75.Sort Colors
- LeetCode --- 75. Sort Colors
- [Leetcode] 75. Sort Colors
- [leetcode] 75.Sort Colors
- 【leetcode】75. Sort Colors
- [leetcode] 75. Sort Colors
- Leetcode 75. Sort Colors
- *LeetCode 75. Sort Colors
- 75. Sort Colors LeetCode
- Leetcode 75. Sort Colors
- [LeetCode]75. Sort Colors
- LeetCode 75. Sort Colors
- LeetCode *** 75. Sort Colors
- leetcode 75. Sort Colors
- LeetCode 75. Sort Colors
- leetcode-75. Sort Colors
- [leetcode]75. Sort Colors
- LeetCode-75.Sort Colors
- unity3D引擎:2D游戏自动瞄准算法实现
- Dapper的扩展这个你知道嘛?
- 树莓派3B-raspbian系统安装
- oracle 权限管理
- 在ununt下安装JDK,eclipse,tomcat
- leetcode 75. Sort Colors
- 抽象工厂模式
- 书单
- 循环神经网络(RNN, Recurrent Neural Networks)介绍
- JS事件简单总结
- 多核处理器与向量处理器
- 强连通分量入门——UVA
- 读华为敏捷转型有感
- 3.4 T2(NOIP 2015)