Day05--颜色分类(Python实现)

Day05--颜色分类(Python实现)
这里运用偷懒的方法,先通过遍历count出0、1、2的个数,然后通过个数分别赋值,代码如下:

class Solution:
    def sortColors(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        count0, count1, count2 = 0, 0, 0
        for num in nums:
            if num == 0:
                count0 += 1
            elif num == 1:
                count1 += 1
            else:
                count2 += 1
        
        for i in range(count0):
            nums[i] = 0
        for j in range(count1):
            nums[count0 + j] = 1
        for k in range(count2):
            nums[count0 + count1 + k] = 2