测评会员优惠活动进行中 · 开通 VIP,有效期内测评不限次 VIP 优惠中 · 测评不限次 立即查看

A22789. 最近的数

填空题 中等

题目描述

最近的数

题目描述

给定一个整数 X 和一个长度为 N 的整数序列 p1, p2,……, pn。请找出不在该序列中的整数(不一定为正数)中,与 X 的差的绝对值最小的那个整数。若存在多个满足条件的整数,则输出其中最小的一个。

输入格式

第一行:两个整数 X , N;

第二行:N 个整数表示  p1, p2,……, pn

注意:当 N = 0 时,第二行为空行。

输出格式

输出满足条件的整数。

输入样例#1

6 5
4 7 10 6 5

输出样例#1

8

输入样例#2

6 5
4 7 8 6 5

输出样例#2

3

参考答案

#include <iostream> #include <algorithm> #include <cstdio> const int inf = 0x3f3f3f3f; int main() { int x, n; std::cin >> x >> n; int a[1001] = {0}; int re; for (int i = 0; i < n; i++) { std::cin >> re; a[re]++; } int ans, res, ans1 = inf, res1; for (int i = x; i <= 101; i++) { if (a[i] == 0) { ans = i - x; res = i; break; } } for (int i = x - 1; i >= 0; i--) { if (a[i] == 0) { ans1 = std::min(ans1, x - i); res1 = i; break; } } if (ans < ans1) std::cout << res << '\n'; else std::cout << res1 << '\n'; return 0; }
上一题 下一题