缺失数
Case Time Limit: 3200 MS (Others) / 6400 MS (Java) Case Memory Limit: 256 MB (Others) / 512 MB (Java)
Problem Description
输入N个整数,求缺失的最小正整数,即1、2、3、...中不存在于这N个整数中的最小数。例如-3、-1、0、1、2、4、6中缺失的最小正整数为3。注意这N个整数可能无序。
Input
每个输入文件一组数据。
对每组数据,第一行为一个整数N(0 <= N <= 10^7),表示整数的个数;
第二行为N个整数,每个整数的绝对值都不超过10^18。
Output
输出一个正整数,即缺失的最小正整数。
Sample Input
7 -3 -1 0 1 2 4 6
Sample Output
3
Author
Shoutmon
Source
18浙大考研机试模拟赛
#include <cstdio>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long LL;
const int MAXN = 10000010;
int n;
LL a[MAXN];
vector<int> vec;
int getFirstMissingPositiveInteger(){
for(int i = 1;i <= n; i++){
while(a[i]>0 && a[i]<=n && a[i] != a[a[i]] ){
swap(a[i],a[a[i]]);
}
}
for(int i=1;i<=n;i++){
if(a[i] != i){
return i;
}
}
return n+1;
}
int main(){
scanf("%d",&n);
for(int i = 1; i <= n; i++){
scanf("%lld",&a[i]);
}
printf("%d\n",getFirstMissingPositiveInteger());
return 0;
}
仍然是复写晴神答案,我最初尝试用hash来写,很快写完,但数值太大,没能通过
唔,对空间复杂度和时间复杂度仍然掌握不好,我不知道为什么自己的答案就无法运行,还需多加学习。