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.
Topic:
To an unordered array, find the first positive integer that does not appear in the array starting from 1.
Requires O (n) time complexity and constant space complexity.
Ideas: 1, method one:
Sort first and then iterate through the array to find the first positive integer that does not appear. But the time complexity is O (NLOGN), does not meet the requirements.
The implementation is as follows:
#include <iostream>#include<algorithm>using namespacestd;intFirstmisspositive (intA[],intN) {Sort (a,a+n,less<int>()); intI=0; while(a[i]<=0) i++; intj=1; while(i<N) { if(i<n-1&& a[i]==a[i+1]) i++; if(A[I]!=J) Break; I++; J++; } returnJ;}intMain () {inta[]={4,4,3,-1,-2,2,1}; intn=sizeof(A)/sizeof(a[0]); cout<<firstmisspositive (a,n); return 0;}
2, Method Two:
For positive integer a[i], if you place it in an array that satisfies the position of a[i]=i+1, then I is the first positive integer that does not appear if a[i]==i+1 is not satisfied at a location.
- Iterate through the array,
- When encountering a positive integer less than n (n array size), if it satisfies a[i]=i+1, then skips, i++, if not satisfied, swaps it to its place, that is, swap (a[i],a[a[i]-1]);
- When a number less than 0 or greater than n is encountered, or the position to be swapped already has a value that satisfies the condition (a[i]==a[a[i]-1] (this happens when there are duplicate numbers in the array), skip, i++, because there is no suitable position to swap with them.
- Iterate over the array again if a[i]! =i+1, then I is the first positive integer that does not appear.
The code is as follows:
classSolution { Public: voidSwapint&a,int&b) { inttmp; TMP=A; A=b; b=tmp; } intFirstmissingpositive (vector<int>&nums) { intn=nums.size ();//if (n==0) return 1; intI=0; while(i<N) { if(nums[i]==i+1|| nums[i]==nums[nums[i]-1] || nums[i]<=0|| Nums[i]>N) I++; Elseswap (Nums[i],nums[nums[i]-1]); } for(i=0; i<n;i++){ if(nums[i]!=i+1) Break; } returni+1; }};
(leetcode) First Missing Positive