1. 程式人生 > >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