Very Simple Python Solutions


  • 0
    S
    class Solution(object):
        def firstMissingPositive(self, nums):
            n = len(nums)
            exists = [0] * (n + 2)
    
            for i, num in enumerate(nums):
                if 1 <= num <= n + 1:
                    exists[num % (n + 1)] = -1
    
            for i in range(1, n + 2):
                if exists[i] != -1:
                    return i
    
    
    class Solution(object):
        def firstMissingPositive(self, nums):
            n, i = len(nums), 0
    
            while i < n:
                num = nums[i]
                if num != i + 1 and 1 <= num <= n and num != nums[num - 1]:
                    nums[i], nums[num - 1] = nums[num - 1], nums[i]
                else:
                    i += 1
    
            for i, num in enumerate(nums):
                if num != i + 1:
                    return i + 1
            else:
                return n + 1

  • 0
    H

    Your first solution: isn't it O(n) space?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.