Lintcode148 Sort Colors solution 题解
来源:互联网 发布:yellow submarine 知乎 编辑:程序博客网 时间:2024/05/17 15:21
【题目描述】
Given an array with n objects colored red,white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0,1, and 2 to represent the color red, white, and blue respectively.
Notice:
You are not suppose to use the library's sort function for this problem.
You should do it in-place (sort numbers in the original array).
给定一个包含红,白,蓝且长度为 n 的数组,将数组元素进行分类使相同颜色的元素相邻,并按照红、白、蓝的顺序进行排序。
我们可以使用整数 0,1 和 2 分别代表红,白,蓝。
【注】:1、不能使用代码库中的排序函数来解决这个问题。
2、排序需要在原数组中进行。
【题目链接】
www.lintcode.com/en/problem/sort-colors/
【题目解析】
由于只有三种颜色,那么红色必然在数组的左边,而蓝色必然在数组的右边。
那么我们只需要两个变量记录红色所在区域的边界[0, i], 以及蓝色所在区域的边界[j,n-1]。那么白色所在的区域必然为(i,j).
怎样得到红蓝两色的边界呢?
初始化: 红色边界i=0; 蓝色边界j=n-1;
为了加速运算,可以预处理,分别从左至右,从右至左,找到红蓝边界,缩小搜索范围。见代码line[3,4]
假设当前位置为k
(1) A[k] 为红色, 那么将该元素同红色右边界的后一个数互换。 A[k] ~ A[i++]
(2) A[k] 为蓝色, 那么将该元素同蓝色左边界的前一个数互换。 A[k] ~ A[j--]
(3) A[k] 为白色, 那么当前无需交换, k=k+1;
终止条件 k>j 此时不可能出现白色,可以退出了。
【参考答案】
www.jiuzhang.com/solutions/sort-colors/
- Lintcode148 Sort Colors solution 题解
- Lintcode143 Sort Colors || solution 题解
- LeetCode题解:Sort Colors
- [题解][LeetCode][Sort Colors]
- leetcode_75. Sort Colors题解
- LeetCode Sort Colors (One Pass Solution)
- Lintcode98 Sort List solution 题解
- LintCode148
- LeetCode 题解(5):Sort Colors
- Lintcode49 Sort Letters by Case solution 题解
- Lintcode173 Insertion Sort List solution 题解
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- ≪统计学习精要(The Elements of Statistical Learning)≫课堂笔记(四)
- MySql修改 表名
- (学习java)写一个完整的程序,实现随机生成20个元素的链表,快速查找中间结点的值并显示
- C语言 二级指针详解及示例代码
- 根据两个经纬度坐标计算两个坐标间的距离
- Lintcode148 Sort Colors solution 题解
- 08-面向对象(继承-Java中的单继承和多重继承). 11-面向对象(继承-子父类中成员变量的内存图解) 11-面向对象(继承-子父类中成员变量的内存图解2
- 可以用作javascript异步模式的编程的方法
- 数据库系统概论学习笔记(一)---数据模型
- 银行家算法
- 左右为难
- 客户端架构
- VS2008下Qt4编译MySQL驱动
- 微信抢票实战总结