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.
这类题目的思路一般都是复用原数组,并且将数组中的元素hash到原数组中,看过陈利仁老师所说的“元神归位法”,这道题目就很简单了。
以下是我的代码:
class Solution{
public:
int firstMissingPositive(int A[], int n){
if(A==NULL || n<0) throw "Invalid Arguments!";
if(n==0) return 1;
int i = 0;
// Find the smallest num Greater than 0.
int minNum = INT_MAX;
for(i=0; i<n; i++){
if(A[i]<minNum&&A[i]>0){
minNum = A[i];
}
}
if(minNum>1||minNum<=0){
return 1;
}
// Hash the num using A[i]-minNum.
for(i=0; i<n; ){
if((A[i]!=minNum+i)&&
(A[i]>0)&&
(A[i]<minNum+n)&&
(A[A[i]-minNum]!=A[i])){
swap(A,i,A[i]-minNum);
}
else{
i++;
}
}
for(i=0; i<n; i++){
if(A[i]!=i+minNum){
break;
}
}
return (i+minNum);
}
private:
void swap(int A[], int i, int j){
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
};