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.
This is the method of count sort.
First, let's review the Count sort.
A positive integer is known to have no array. First, iterate over to get the maximum value, build an counter array.
Then the number of counter inside is assigned to the original array in turn.
The code is as follows
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 adef main (): a=[8,9,22,1,2,2,7] counts (A) if __name __== "__main__": Main ()
The idea of this problem is similar to the Count sort, first arrange the array in order from small to large, and finally if which element does not conform to a[i]=i+1 return 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
Missing Positive Leetcode Python