75. Sort Colors

题目:

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.

链接: http://leetcode.com/problems/sort-colors/

一开始直接照搬3-way quicksort(没有randomly shuffle),效率很低,因为有recursion所以时间复杂度NlgN

3-way quicksort主要用在有比较多duplicate情况下,这道题可以更加简化,因为一共只有三个值。但是i应该从第一个位置开始,原因是,在3-way当中我们可以随便把任一个值当做partition element,区别只是在partition的位置而已,经过recurstion之后最终肯定会排序好。而这道题我们只有遍历一遍,所以必须保证每个值都在排序好的位置上,所以第一个值也要在循环体内。

此解法当中的lo指向下一个可能的1(为第一个元素或者之前都是0)

 1 class Solution(object):
 2     def sortColors(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: void Do not return anything, modify nums in-place instead.
 6         """
 7         if len(nums) <= 1:
 8             return 
 9         lo = 0
10         hi = len(nums) - 1
11         i = 0
12 
13         while i <= hi:
14             if nums[i] < 1:
15                 nums[lo], nums[i] = nums[i], nums[lo]
16                 i += 1
17                 lo += 1
18             elif nums[i] > 1:
19                 nums[hi], nums[i] = nums[i], nums[hi]
20                 hi -= 1
21             else:
22                 i += 1
23         return
原文地址:https://www.cnblogs.com/panini/p/5801714.html