Skip to content

Latest commit

 

History

History
55 lines (40 loc) · 882 Bytes

41. First Missing Positive.md

File metadata and controls

55 lines (40 loc) · 882 Bytes

41. First Missing Positive

https://leetcode.com/problems/first-missing-positive/

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Follow up:

Your algorithm should run in O(n) time and uses constant extra space.

代码

class Solution(object):
    def firstMissingPositive(self, A):
        """
        :type nums: List[int]
        :rtype: int
        """
        A.append(0)
        n = len(A)
        for i in range(len(A)):
            if A[i] < 0 or A[i] >= n:
                A[i] = 0
        for i in range(len(A)):
            A[A[i] % n] += n
        for i in range(1, len(A)):
            if A[i] / n == 0:
                return i
        return n