在一个非降序列中,查找与给定值最接近的元素。

Input
第一行包含一个整数n,为非降序列长度。1 <= n <= 100000。
第二行包含n个整数,为非降序列各元素。所有元素的大小均在0-1,000,000,000之间。
第三行包含一个整数m,为要询问的给定值个数。1 <= m <= 10000。
接下来m行,每行一个整数,为要询问最接近元素的给定值。所有给定值的大小均在0-1,000,000,000之间。
Output
m行,每行一个整数,为最接近相应给定值的元素值,保持输入顺序。若有多个值满足条件,输出最小的一个。
Sample Input

1
2
3
4
5
3
2 5 8
2
10
5

Sample Output

1
2
8
5

ac代码
参考链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5+6;
int a[MAXN] = {};

int main() {
int n,m;
scanf("%d",&n);
for(int i=0;i<n;++i){
scanf("%d",&a[i]);
}
scanf("%d",&m);
for(int i=0;i<m;++i){
int t;
scanf("%d",&t);
if(t<=a[0]){
printf("%d\n",a[0]);
}else if(t>=a[n-1]){
printf("%d\n",a[n-1]);
}
else{
int l=0,r=n;
while(l<r){
int min=(l+r)/2;
if(a[min]>t){
r=min;
}else{
l=min+1;
}
}
int ans=l;//跟下面这函数相同的作用 找到第一个比t大的数
// int ans=upper_bound(a,a+n,t)-a;
if(a[ans]-t<t-a[ans-1]){
printf("%d\n",a[ans]);
}else{
printf("%d\n",a[ans-1]);
}
}
}
return 0;
}