卖萌的弱渣

I am stupid, I am hungry.

First Missing Positive

First Missing Positive

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

Example

Given [1,2,0] return 3, and [3,4,-1,1] return 2.

Challenge

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

Solution

(First-Missing-Positive.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
    # @param A, a list of integers
    # @return an integer
    def firstMissingPositive(self, A):
        # write your code here
        if A == None or len(A) == 0:
            return 1
        length = len(A)
        # The first missing positive should in [1...N]
        # Scan A, if A[i] <= 0 or A[i] > N, we assign a dummy integer -1

        for i in range(length):
            if A[i] <= 0 or A[i] > length:
                A[i] = -1

        # Use Aray A as hash table, if A[i] in [1...N], we put A[i] to A[A[i]-1]
        # A[i] != A[A[i]-1] is used for removing dead loop if A = [1]
        for i in range(length):
            while A[i] != -1 and A[i] != A[A[i]-1]:
                tmp = A[A[i]-1]
                A[A[i]-1] = A[i]
                A[i] = tmp
        # Scan the new A, find A[i] != i+1
        for i in range(length):
            if A[i] != i+1:
                return i+1

        # for case: [1,2,3], missing is 4
        return length+1