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.
incomplete.
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i=0;
while(i<n) {
if( i==A[i]-1) {
i++;
continue;
} else if( A[i] != A[A[i]-1] ) {
swap( A[i], A[ A[i]-1]);
continue;
}
i++;
}
i=0;
while( i<n && i==A[i]-1) i++;
return i+1;
}
template<class T>
void swap(T & a, T & b){
T temp = a;
a = b;
b = temp;
}
};
second try works.
public class Solution {
public int firstMissingPositive(int[] A) {
// Start typing your Java solution bemain() function
int len = A.length;
if(len<1) return 1;
int i=0;
while(i<len){
int ai = A[i];
if(ai>0 && ai<len && ai!=A[ai]) {
A[i] = A[ai];
A[ai] = ai;
continue;
}
++i;
}
i=1;
while(i<len && A[i]==i) i++;
if(i<len) return i;
return A[0]==len ? len+1 : len;
}
}