问题描述:
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.
Note:
You are not suppose to use the library's sort function for this problem.
问题分析:
数组排序的平均时间复杂度是O(nlgn),该题需要在O(n)时间复杂度内完成。
因为数据的特点:输入序列中的元素只有三种类型,所以能够在线性时间内
完成。两个指针red, blue可以将数组划分成为三段。
初始值:
red = -1, blue = n, i = red + 1;
(-infinite, red] RED元素
[blue, +infinite) BLUE元素
i in (red, blue), (red, i) GREEN元素, 该条可以认为是下面迭代过程的循环不变式迭代过程:
while (i < blue)
{
if (a[i] == BLUE && --blue != i)
{ swap(a[i], a[blue]); continue; }
if (a[i] == RED && ++red != i)
{ swap(a[i], a[red]); }
i++;
}
本文介绍了一种在O(n)时间复杂度内对红、白、蓝三色进行排序的算法,通过使用两个指针来划分数组,使得相同颜色的对象相邻,并按红、白、蓝的顺序排列。

685

被折叠的 条评论
为什么被折叠?



