1. 程式人生 > >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