Lintcode148 Sort Colors solution 题解

来源:互联网 发布:yellow submarine 知乎 编辑:程序博客网 时间:2024/05/17 15:21

【题目描述】

Given an array with 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/



原创粉丝点击