Missing Positive (MAP)

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.

Idea: N number, the possible maximum positive integer is n, so you can use this n number as the hash value. But there is an extra space for O (n).

The solution is to reuse a[], first a[i] negative numbers are removed (marked as n+1), and secondly, when traversing to an integer cur, the a[cur] becomes the opposite number, so that the a[i]<0 I position I appeared, but also to ensure that the original value is not destroyed (can be obtained by ABS (A[i]) obtained.

classSolution { Public:    intFirstmissingpositive (intA[],intN) {inti;  for(i =0; I < n; i++)            if(a[i]<=0) A[i] = n+1;  for(i =0; I < n; i++) {            if(ABS (A[i]) <= N) {//ABS is required because in the FOR loop we change the value of [1,n] to a negative number                intCur = ABS (A[i])-1; A[cur]= -ABS (A[cur]); }        }         for(i =0; I < n; i++) {            if(A[i] >0)returni+1; }        returnn+1; }};

Missing Positive (MAP)

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.