14、查找最接近的元素

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

输入格式

第一行包含一个整数 n,为非降序列长度。1≤n≤100000。

第二行包含 n个整数,为非降序列各元素。所有元素的大小均在 0∼1,000,000,000 之间。

第三行包含一个整数 m,为要询问的给定值个数。1≤m≤10000。

接下来 m行,每行一个整数,为要询问最接近元素的给定值。所有给定值的大小均在 0 ∼1,000,000,000 之间。

输出格式

m 行,每行一个整数,为最接近相应给定值的元素值,保持输入顺序。若有多个值满足条件,输出最小的一个。

样例输入

3
2 5 8
2
10
5

样例输出

8
5

解题思路(二分查找):

●res==-1,说明b比数组a中的所有元素都大,返回a[n];

●res==1,说明b比数组a中的所有元素都小,返回a[1];

●当res!=1 && res!=-1时,a[res]大于等于b,a[res-1]是小于b的最大元素,比较二者与b的差值;若b-a[res-1]<=a[res]-b,则返回a[res-1],否则返回a[res]。

#include <bits/stdc++.h>
using namespace std;
int n,m,a[100001],b;
int solve(int x){
    int L=1,R=n,mid,res=-1;
    while(L<=R){
        mid=(L+R)/2;
        if(a[mid]>=x){
            R=mid-1;
            res=mid;
        }else{
            L=mid+1;
        }
    }
    return res;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
    }
    cin>>m;
    while(m--){
        cin>>b;
        int res=solve(b);
        if(res==-1){
            cout<<a[n]<<endl;
        }else if(res==1){
            cout<<a[1]<<endl;
        }else{
            if(b-a[res-1]<=a[res]-b){
                cout<<a[res-1]<<endl;
            }else{
                cout<<a[res]<<endl;
            }
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46027166/article/details/121940423