【PAT甲级】The Missing Number
- 2019 年 11 月 8 日
- 笔记
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_42449444/article/details/89448094
Problem Description:
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来记录所有出现在输入列表中的正整数啊,然后再无脑for循环找出第一个(也就是最小的那个)没有出现在set中的正整数即可。
AC代码:
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; set<int> s; //用来存放出现过的正整数 for(int i = 0; i < N; i++) { int temp; cin >> temp; if(temp > 0) //向set中插入正整数 { s.insert(temp); } } int ans; //第一个没出现过的正整数ans for(int i = 1; ; i++) { if(s.count(i) == 0) //找到第一个没出现过的正整数 { ans = i; break; } } cout << ans << endl; return 0; }