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.
高效算法:O(n) 时间复杂度,O(1)空间复杂度
实现:
- int firstMissingPositive(int A[], int n) {
- if(n<=0) return 1;
- for(int j=0;j<n;) {
- if(A[j]>0 && A[j]<n && A[j]!=j && A[A[j]]!=A[j]) {
- swap(A[j],A[A[j]]);
- }else {
- j++;
- }
- }
- for(int j=1;j<n;j++) {
- if(A[j]!=j) return j;
- }
- if(A[0] == n) return n+1;
- else return n;
- }

浙公网安备 33010602011771号