首页 > 代码库 > 41. First Missing Positive Leetcode Python

41. First Missing Positive Leetcode Python

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


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


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



这题用的是count sort 的方法。

首先我们来复习一下count sort

已知一个正整数还未排列数列。 先遍历一遍得到最大值,建一个counter数组。

再将counter里面的数依次赋值到原来的数组当中去。

代码如下

def counts(A):
    maxval=-1000
    
    for elem in A:
        if maxval<elem:
            maxval=elem
    
    counter=[0]*(maxval+1)
    for elem in A:
        counter[elem]+=1
    
    iter=0
    for i in range(len(counter)):
        while counter[i]>0:
            print i
            A[iter]=i
            iter+=1
            counter[i]-=1
    print A

def main():
    A=[8,9,22,1,2,2,7]
    counts(A)

if __name__=="__main__":
    main()
    

这题的想法和count sort类似,先把数组按照从小到大排列一遍,最后如果哪个元素不符合A[i]=i+1 就返回 i+1

class Solution:
    # @param A, a list of integers
    # @return an integer
    def firstMissingPositive(self, A):

        if len(A)==0:
            return 1
        i=0
        while i<len(A):
            if A[i]<=len(A) and A[i]>0 and A[A[i]-1]!=A[i]:
                tmp=A[A[i]-1]
                A[A[i]-1]=A[i]
                A[i]=tmp
                i-=1
            i+=1
        i=0        
        while i<len(A):
            if A[i]!=i+1:
                return i+1
            i+=1
        return len(A)+1        





41. First Missing Positive Leetcode Python