✍个人博客:https://blog.csdn.net/Newin2020?spm=1011.2415.3001.5343
📚专栏地址:PAT题解集合
📝原题地址:题目详情 - 1144 The Missing Number (pintia.cn)
🔑中文翻译:漏掉的数字
📣专栏定位:为想考甲级PAT的小伙伴整理常考算法题解,祝大家都能取得满分!
❤️如果有收获的话,欢迎点赞👍收藏📁,您的支持就是我创作的最大动力💪
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;
}