"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