leetcode-75-顏色分類

問題

給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。

此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。

注意:
不能使用代碼庫中的排序函數來解決這道題。

`
示例:

輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]
`

解題思路

分別找出0,1,2有多少個,之後再賦值到所需要到列表中。

代碼

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        tmp0 = 0
        tmp1 = 0
        tmp2 = 0
        for dig in nums:
            if dig == 0:
                tmp0 += 1
            elif dig == 1:
                tmp1 += 1
            else:
                tmp2 += 1

        nums[:tmp0] = [0]*tmp0
        nums[tmp0:(tmp0+tmp1)] = [1]*tmp1
        nums[(tmp0+tmp1):] = [2]*tmp2

方法二:
利用兩個指針定位和替換0和2,之後的1自然也就放置好了。但只能針對這個情況。其他不實用。

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

                p2 -= 1
            else:
                curr += 1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章