美文网首页
python实现leetcode之75. 颜色分类

python实现leetcode之75. 颜色分类

作者: 深圳都这么冷 | 来源:发表于2021-09-11 09:16 被阅读0次

    解题思路

    三路快速排序,假设划分的元素是1
    然后保证
    [0...red)是0
    [red...white)是1
    [white...blue]是未检查区
    (blue...end-1)是2

    75. 颜色分类

    代码

    class Solution(object):
        def sortColors(self, nums):
            """
            :type nums: List[int]
            :rtype: None Do not return anything, modify nums in-place instead.
            """
            # [0-red-red][red-red-white][white-mix-blue][blue-blue-end]
            red, white, blue = 0, 0, len(nums) - 1
            while white <= blue:
                white = max(white, red)
                if nums[red] == 0:
                    red += 1
                    white += 1
                elif nums[blue] == 2:
                    blue -= 1
                elif nums[white] == 1:
                    white += 1
                elif nums[white] == 0:
                    nums[red], nums[white] = nums[white], nums[red]
                    red += 1
                elif nums[blue] == 0:
                    nums[red], nums[blue] = nums[blue], nums[red]
                    red += 1
                else:
                    nums[white], nums[blue] = nums[blue], nums[white]
                    white += 1
                    blue -= 1
    
    效果图

    相关文章

      网友评论

          本文标题:python实现leetcode之75. 颜色分类

          本文链接:https://www.haomeiwen.com/subject/bunnwltx.html