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存储,当数字出现,将对应的位置为true,但是有几点要注意:
1)由于正整数由1开始,而数组下标由0开始,所以设hash大小为n+2,目的是多容纳0和数组中所有数字都是正整数且不重复的情况,这是要求的值肯定是n+1,考虑到最多需要保存n+2个数字,所以大小设为n+2.
class Solution {
public:
int firstMissingPositive(int A[], int n) {
if(n==0)
return 1;
bool *hash=new bool[n+2];
memset(hash,false,sizeof(bool)*(n+2));
for(int i=0;i<n;i++)
{
if(A[i]>=0)
hash[A[i]]=true;
}
for(int i=0;i<n+2;i++)
{
if(!hash[i]&&i!=0)
return i;
}
}
};