1144 The Missing Number (20 分)
Given N integers, you are supposed to find the smallest positive integer that is NOT in the given list.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤105). Then N integers are given in the next line, separated by spaces. All the numbers are in the range of int.
Output Specification:
Print in a line the smallest positive integer that is missing from the input list.
Sample Input:
10
5 -25 9 6 1 3 4 2 5 17
Sample Output:
7
题目大意:
给出长度为n的整数序列,找到不在序列中最小的正整数。
思路:
- 以n为界,那么可能的情况有1~n内就存在缺省的正整数,或者1~n都被填满了必然是n + 1 为结果。
参考代码:
#include<vector>
#include<cstdio>
using namespace std;
vector<int> cnt, a;
int n;
int main(){
scanf("%d", &n);
cnt.resize(n + 1), a.resize(n + 1);
for(int i = 0; i < n; ++i){
scanf("%d", &a[i]);
if(a[i] > 0 && a[i] <= n) cnt[a[i]] = 1;
}
for(int i = 1; i <= n; ++i)
if(!cnt[i]){
printf("%d", i);
return 0;
}
printf("%d", n + 1);
return 0;
}