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.
1、不考虑时间复杂度,可以用排序做,时间复杂度为O(logn)
排序版,12ms过
class Solution {
public:
int firstMissingPositive(int A[], int n) {
sort(A,A+n);
int cnt=0;
for(int i=0;i<n;i++){
if(A[i]<=cnt)continue;
cnt++;
if(cnt!=A[i])return cnt;
}
return cnt+1;
}
};12ms过
class Solution {
public:
int firstMissingPositive(int A[], int n) {
vector<bool> B(n+1,0);
for(int i=0;i<n;i++){
if(A[i]<=0)continue;
B[A[i]]=1;
}
for(int i=1;i<=n;i++){
if(!B[i])return i;
}
return n+1;
}
};3、题目的最后一行,要求O(n)实际上暗示了用hash,但是又说要contant space,就没法再开新空间来建hash。
正好这个题目中处理的是1到n的数据,提供了一个将输入的数组同时用作hash表的可能性。
于是算法就是:
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int i=0;i<n;i++)if(A[i]<=0)A[i]=INT_MAX;
for(int i=0;i<n;i++){
int a=abs(A[i]);
if(a<=n)
A[a-1]=-abs(A[a-1]);
}
for(int i=0;i<n;i++)
if(A[i]>0)return i+1;
return n+1;
}
};LeetCode OJ:First Missing Positive
原文:http://blog.csdn.net/starcuan/article/details/18865515