欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

leetcode75. Sort Colors python代码版

程序员文章站 2024-02-23 19:48:04
...

原题

方法一:
采用三个变量分别计数0,1,2所出现的次数。然后将0,1,2按照这个次数重新填入原列表。

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        c0 = 0
        c1 = 0
        c2 = 0
        for num in nums:
            if num == 0:
                c0 += 1
            if num == 1:
                c1 += 1
            if num == 2:
                c2 += 1
        i = 0
        while c0 > 0:
            nums[i] = 0
            c0 -= 1
            i += 1
        while c1 > 0:
            nums[i] = 1
            c1 -= 1
            i += 1
        while c2 > 0:
            nums[i] = 2
            c2 -= 1
            i += 1

方法二:
采用前后两头约束的方式来约束游标i,当置换过前后的约束点后,对约束点进行更新。

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        
        zero, second = 0, len(nums)-1
        
        i = 0
        while i <= second:
            while nums[i]==2 and i < second:
                nums[i], nums[second] = nums[second], nums[i]
                second -= 1
            while nums[i]==0 and i > zero:
                nums[i], nums[zero] = nums[zero], nums[i]
                zero += 1
            i += 1