leetcode color sort

来源:互联网 发布:韩路淘宝店叫什么 编辑:程序博客网 时间:2024/06/11 02:15

问题描述:

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++;}


0 0