mycode

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 1
        nums = sorted(nums)
        max_n = max(nums)
        for i in range(1,max_n+1):
            if i not in nums:
                return i
        return max_n + 1
Runtime Error Message:Line 11: MemoryError
Last executed input:[2147483647]
 
44.76%
class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 1
        if 1 not in nums:
            return 1
        else:
            nums = sorted(set(nums))
            pos = nums.index(1)
            if pos == len(nums) -1:
                return 2
            else:
                nums[:] = nums[pos:]
                for i in range(1,len(nums)):
                    if not i+1 == nums[i]:
                        return i + 1
                return len(nums) + 1

 

参考

class Solution(object):
    def firstMissingPositive(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        l = range(0,-len(nums)-1,-1)   [0,-1,-2,-3...]
        print(l)
        if not len(nums):
            return 1
        
        for n in nums:
            if n < len(l) and n > 0:
                l[n] = n
                                
        for n in l:
            if n < 0:
                return -n
            
        return len(l)