[leetcode:python]75.Sort Colors

本文介绍了一种不使用库函数的三色排序算法,通过将数组中的0、1、2分别代表红、白、蓝三种颜色并按顺序排列,提供两种实现方法:一种是通过将0放到前面,2放到后面实现;另一种是利用Lomuto分区算法,通过一次遍历完成排序。

题目:
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.
题意:
用0,1,2表示不同的三种颜色,给定一个颜色序列,写程序使得相同的颜色处于相邻的位置。
不能使用库的函数。

方法一:性能42ms
把0都放前面,2都放后面

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        if nums== []:
            return 
        p0 = 0
        p2 = len(nums) - 1
        i = 0
        while i <= p2:
            if nums[i] == 2:
                nums[i], nums[p2] = nums[p2], nums[i]
                p2 -= 1
            elif nums[i] == 0:
                nums[i], nums[p0] = nums[p0], nums[i]
                p0 +=1
                i += 1
            else:
                i += 1

方法二:性能35ms

class Solution(object):
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        # Using Lomuto's partition algorithm
        # store value for each iteration
        # In-place one pass solution O(n) O(1)
        # No swap required
        # [0, i) are 0's
        # [i, j) are 1's
        # [j, k) are 2's
        i, j = 0, 0
        for k in range(len(nums)):
            cur = nums[k]   # store value
            nums[k] = 2 # make color blue
            if cur < 2: # if red or white
                nums[j] = 1 # make white
                j += 1
            if cur == 0:
                nums[i] = 0
                i += 1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值