1144 The Missing Number
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
题意
给定一个数组,找到其中未出现的最小正整数。
思路
我们可以将所有数存进一个 set
容器,它会自动帮我们去掉重复的数字并排序,然后再从 1
往后查找,第一个没有在 set
中找到的数字就是我们要找的最小正整数。
代码
#include<bits/stdc++.h> using namespace std; const int N = 100000; unordered_set<int> res; int main() { int n; cin >> n; //将正数放入容器 for (int i = 0; i < n; i++) { int x; cin >> x; res.insert(x); } //找到最小未出现的正整数 int t; for (t = 1; t <= N; t++) { if (res.count(t) == 0) { cout << t << endl; return 0; } } cout << t << endl; return 0; }