leetcode_075 Sort Colors
来源:互联网 发布:薛之谦在淘宝开的店铺 编辑:程序博客网 时间:2024/06/16 11:52
题目分析:给定一个数组,数组中的元素只可能为0,1,2,其中0代表红色,1代表白色,2代表蓝色。请按照红、白、蓝的顺序排好。不能使用排序算法实现。
解题思路:
一遍扫描遍历数组,需要三个指针进行记录,详细如下:
1)从开始起第一个不确定为0的位置;
2)遍历指针所处的当前位置;
3)从末尾起第一个不确定是否为2的位置;
如果当前指针指向的值为0,则与前面指针指向的值进行交换,并向前移动两个指针的位置;
如果当前指针指向的值为1,则将当前指针向前移;
如果当前指针指向的值为2,则与后面指针指向的值进行交换,并向前移动指向后面的指针。
class Solution{public:// 交换两个数函数 void swap(int &a, int &b){int temp = a;a = b;b = temp;}//直观理解 void sortColors1(vector<int> &nums){int len = nums.size();if (len <= 1)return ;int i = 0;int j = len - 1;int cur = i;while (cur <= j){// 当前指针指向值为0时,当前指针与指向第一个不确定为0的指针交换,同时向前移动连个指针 if (nums[cur] == 0){swap(nums[i++], nums[cur++]);}// 当前指针指向值为2时,当前指针与指向第一个不确定为2的指针交换,同时向前移动后面的指针 else if (nums[cur] == 2){if (cur < j){swap(nums[j--], nums[cur]);}elsereturn ;}// 当前指针指向值为0时,向前移动当前真真 else{cur++;}}}// 与上面的原理一样,只是便于理解。 void sortColors(vector<int> &nums){int zero_end = -1;int two_begin = nums.size();int i = 0;while (i < two_begin){if (nums[i] == 0 && i != ++zero_end){swap(nums[i], nums[zero_end]);}else if (nums[i] == 2 && i != --two_begin){swap(nums[i], nums[two_begin]);}elsei++;} }};
0 0
- leetcode_075 Sort Colors
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- 电子邮件协议之SMTP、POP3和IMAP
- ios随机设置颜色代码
- web-yestem(伊思腾)-企业门户-数据库设计
- PAT 乙级 1033. 旧键盘打字
- mysql-5.6.29-winx64 安装配置过程
- leetcode_075 Sort Colors
- 【设计模式】单例模式实践应用
- 通过贝塞尔路径画一条线
- 最全VR产业链全景图
- Spring Batch(6) : ItemReader & ItemWriter
- 51 nod 1092 回文字符串
- 292. Nim Game
- 绘图时候截取部分绘制
- 计算机