75. Sort Colors

本文针对LeetCode上的三色排序问题提出了一种高效的解决方案。该算法避免使用库中的排序函数,通过一次遍历将数组中的0、1、2分别对应红色、白色、蓝色进行排序,确保相同颜色的对象相邻且按红白蓝顺序排列。

题目:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值