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.
class Solution {
public:
int firstMissingPositive(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i;
int *p=new int[n];
memset(p,0,sizeof(int)*n);
for(i=0 ; i<n ; i++){
if(A[i]>0 && A[i]<=n)
p[A[i]-1]=1;
}
for(i=0;i<n;i++){
if(p[i]==0)
return i+1;
}
if(i==n)
return n+1;
}
};
此算法在给定无序整数数组中找到第一个缺失的正整数,时间复杂度为O(n),使用常数空间。
274

被折叠的 条评论
为什么被折叠?



