leetcode-75色の分類

leetcode-75色の分類

件名の説明:

、赤、白、青、アレイのn個の要素の総数、in situでそれらをソートし、同じ色を持つように隣接する素子と、赤、白、青の順に配置所与。この問題は、我々は、赤、白、青を表す0、1、2の整数を使用します。

解決策1:醜い感じ

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        beg,cur,end=0,0,n-1
        while cur<=end and cur<n:
            while beg<n and nums[beg]%3 == 0:
                beg += 1
            while end>0 and nums[end]%3 == 2:
                end -= 1
            if nums[cur] % 3 == 0 and cur >= beg:
                nums[beg], nums[cur] = nums[cur], nums[beg]
                beg += 1
                if nums[cur] % 3 == 2 and cur <= end:
                    nums[end], nums[cur] = nums[cur], nums[end]
                    end -= 1
            if nums[cur] % 3 == 2 and cur <= end:
                nums[end], nums[cur] = nums[cur], nums[end]
                end -= 1
                if nums[cur] % 3 == 0 and cur >= beg:
                    nums[beg], nums[cur] = nums[cur], nums[beg]
                    beg += 1
            cur += 1
        return nums

対処方法2:

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

おすすめ

転載: www.cnblogs.com/curtisxiao/p/11242552.html