排颜色问题——数组 leetcode lintcode
来源:互联网 发布:追一个女生有多难 知乎 编辑:程序博客网 时间:2024/05/01 03:25
问题描述:
给一个数组,并且数组里面元素的值只可能是0,1,2,然后现在把这个数组排序。
另外一种表述: 现有n个红白蓝三种不同颜色的小球,乱序排列在一起,请通过两两交换任意两个球,使得从左至右,依次是一些红球、一些白球、一些蓝球。
解题思路:
采用快速排序partition的思想,用两个指针将三种颜色间隔开。
下面引用此处内容 July 编程艺术系列中荷兰国旗问题。
一个前指针begin,一个中指针current,一个后指针end,current指针遍历整个数组序列,当
- current指针所指元素为0时,与begin指针所指的元素交换,而后current++,begin++ ;
- current指针所指元素为1时,不做任何交换(即球不动),而后current++ ;
- current指针所指元素为2时,与end指针所指的元素交换,而后,current指针不动,end-- 。
为什么上述第3点中,current指针所指元素为2时,与end指针所指元素交换之后,current指针不能动呢?因为第三步中current指针所指元素与end指针所指元素交换之前,如果end指针之前指的元素是0,那么与current指针所指元素交换之后,current指针此刻所指的元素是0,此时,current指针能动么?不能动,因为如上述第1点所述,如果current指针所指的元素是0,还得与begin指针所指的元素交换。
参考代码:
class Solution{public: /** * @param nums: A list of integer which is 0, 1 or 2 * @return: nothing */ void sortColors(vector<int> &nums) { // write your code here int begin=0, cur = 0; int end = nums.size()-1; //0—红 1—白 2—蓝 while(cur <= end) { if(nums[cur] ==0) { swap(nums[begin], nums[cur]); begin++; cur++; }else if(nums[cur] == 1) { cur++; }else if(nums[cur] == 2) { swap(nums[cur], nums[end]); end--; } } } //交换函数 void swap(int &a, int &b) { int temp = a; a = b; b = temp; }};
1 1
- 排颜色问题——数组 leetcode lintcode
- LintCode : 排颜色 II
- LintCode:排颜色 II
- lintcode ----排颜色 II
- 排颜色 II -LintCode
- lintcode-排颜色II-143
- lintcode(143)排颜色 II
- lintcode刷题——颜色分类
- 数组划分——LintCode
- 最大子数组—Lintcode
- 最小子数组—LintCode
- 合并排序数组 II——LintCode
- Lintcode——两数组的交
- LINTCODE——最大子数组III
- LintCode刷题——背包问题
- 算法——错排问题
- 删除排序数组中的重复数字——LintCode
- 数组剔除元素后的乘积——LintCode
- 网站网页变灰的网页代码怎么实现?
- CentOS 7 笔记
- java读取word目录
- 通过豆瓣Api,输入ISBN获取图书信息
- leetcode Rectangle Area
- 排颜色问题——数组 leetcode lintcode
- 配置jdk 环境变量
- Java中的String类常量池详解
- Tomcat优化实践——网站运维
- Xcode6中使用MJRefresh第三方库
- 关于C#泛型作用的简单说明
- 海事东北赛&&全国邀请赛总结
- 天锐绿盾注册机 使用手册
- 【Java GUI】Java面板基础:JPanel