Missing Positive Leetcode Python

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.