Python Solution with O(1) space and O(n) time with explaination


  • 0

    The current positive numbers should increase like i.If 1 was missed, num != i and num + 1 != i, it will return 1. After the num in nums be >= 0 firstly, the num should be 0 or 1, just num == 1, i++ or num + 1 == i, the i will increase normally. if num not equals i, it will return the missing positive num. My English is not good, please forgive me.

    class Solution(object):
        def firstMissingPositive(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            nums.sort()
            f = i = 1
            for index, num in enumerate(nums):
                if num > 0 and f:
                    f = 0
                if not f:
                    if num == i:
                        i += 1
                    elif num + 1 == i:
                        continue
                    else:
                        return i
            return i
    

  • 0
    N

    Hey @MU001999 ,

    Could you please explain me your solution?

    Thanks :)


  • 0

    @naina0412 The current positive numbers should increase like i.If 1 was missed, num != i and num + 1 != i, it will return 1. After the num in nums be >= 0 firstly, the num should be 0 or 1, just num == 1, i++ or num + 1 == i, the i will increase normally. if num not equals i, it will return the missing positive num. My English is not good, please forgive me.


Log in to reply
 

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