[LeetCode Python3] 41. First Missing Positive 一步步優化

ISimle發表於2020-10-01

Solution 1:Time O(nlogn); Space O(1)

# Time O(nlogn); Space O(1)
class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        nums.sort()
        index, size = 0, len(nums)
        while index < size and nums[index] < 1:
            index += 1
        target = 1
        while index < size and nums[index] == target:
            while index < size and nums[index] == target:
                index += 1
            target += 1
        return target

Solution 2:Time O(n); Space O(n)

# Time O(n); Space O(n)
class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        bucket = set()
        target = 1
        for num in nums:
            if num == target:
                target += 1
                while target in bucket:
                    bucket.remove(target)
                    target += 1
            elif num > target:
                bucket.add(num)
        return target

Solution 3:Time O(n); Space O(1)

解法3來自:https://leetcode.com/problems/first-missing-positive/discuss/872224/JavaPython-Supper-Clean-and-Concise-Time-O(N)-Space-O(1)

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        n = len(nums)
        INF = n + 1
        for i in range(n):
            if nums[i] <= 0:
                nums[i] = INF  # marks zero or negative numbers as infinitive positive numbers
        for i in range(n):
            x = abs(nums[i]) - 1  # use index start with zero
            if x < n:
                nums[x] = -abs(nums[x])  # mark `x` as visited by marking `nums[x]` as negative
        for i in range(n):
            if nums[i] > 0:  # if nums[i] is positive -> number (i+1) is not visited.
                return i + 1
        return n + 1

相關文章