"Leetcode" First Missing Positive (2 solutions)

Source: Internet
Author: User

First Missing Positive

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.

Solution One: O (nlogn) Time and O (1) space

No brain solution--First sort O (Nlogn)

Thoughts are as follows:

1, omit the number of non-positive prefixes.

2. Write down a positive integer to be matched as tag.

Consider repetition, if a[i] equals tag, then tag++

If A[i] is greater than tag, returns the tag

A[i] cannot be less than tag, which can be guaranteed by sequencing.

classSolution { Public:    intFirstmissingpositive (intA[],intN) {if(n = =0)            return 1; Sort (A,a+N); inti =0;  while(I < n && A[i] <=0) I++; if(i = =N)return 1; intTag =1;  for(; i < n; i + +))        {            if(A[i] >tag)//miss the Tag                returntag; Else if(A[i] = =tag)//Next PositiveTag + +; Else                ; }        //I==n, miss the tag        returntag; }};

Solution two: O (n) time and O (n) space

A little thought would tell that an array of n capacity, with a maximum of the positive integers covered, is a continuous 1~n

In other words, a missing positive integer is either present in 1~n or n+1

You can therefore construct an array of size n Tag,tag[i] to record whether i+1 this number appears in a.

Returns N+1 if tag is true, otherwise returns the first tag with a negative label of +1

classSolution { Public:    intFirstmissingpositive (intA[],intN) {if(n = =0)            return 1; //Tag[i] means whether i+1 exists in A//at the most 1~n and then return n+1vector<BOOL> tag (n,false);  for(inti =0; I < n; i + +)        {            if(A[i] >0&& A[i] <=N) tag[a[i]-1] =true; }         for(inti =0; I < n; i + +)        {            if(Tag[i] = =false)                returni+1; }        returnn+1; }};

"Leetcode" First Missing Positive (2 solutions)

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.