"Leetcode" First Missing Positive

Source: Internet
Author: User

"Leetcode" 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.

Find the first positive integer that does not appear

Ideas:

Http://tech-wonderland.net/blog/leetcode-first-missing-positive.html

is to place the positive integer A in the A-1 position, and then start from the beginning, and discover that a[i]! = i + 1 is the desired result.

When we iterate over the array, if we find a[i]! = I, then we'll swap (A[a[i], a[i]) and let A[i] put it in the right place. For a[i after the exchange], we continue this operation until the exchange is meaningless. No meaning indicates that the current number is not positive, or exceeds the array length, or is equal to a[a[i]]. We don't care about where these numbers are ranked. Also consider if the entire array is a continuous positive number, such as a[] = {to}, after our order will become {2, 1}, because a[1] = = 1 (compared to 1), and A[2] out of range, so the function will be considered before 2 has appeared and 2 did not appear, return 2. In order to prevent the correct number of "squeezing" the group, we let A[a[i]-1] and A[i] exchange, and then compare i+1 and A[i].

The code is as follows:

1 classSolution {2  Public:3     intFirstmissingpositive (vector<int>&A) {4         intn=a.size ();5         intI=0, J;6          while(i<N)7         {8             if(a[i]!=i+1&&A[i]>0&&a[i]<=n&&a[i]!=a[a[i]-1])9Swap (a[i],a[a[i]-1]);Ten             Else Onei++; A         } -          for(j=0; j<n;++j) -             if(a[j]!=j+1) the                 returnj+1; -         returnn+1; -     } -};

"Leetcode" First Missing Positive

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.