leetcode12: 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.
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;
}
};
浙公网安备 33010602011771号