Short python solution using abs()


  • 1
    F

    set the index of the corresponding number to negative if the number does not exceed the length of list.

    class Solution(object):
        def firstMissingPositive(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            n = len(nums)
            for i in xrange(n):
                if nums[i] <= 0: nums[i] = len(nums)+1
            for i in xrange(n):
                if abs(nums[i]) <= n: nums[abs(nums[i])-1] = -abs(nums[abs(nums[i])-1])
            for i in xrange(n):
                if nums[i] > 0: return i+1
            return n+1

  • 0
    G

    Really cool solution. Thanks for sharing.


Log in to reply
 

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