【二分查找】01:查找最接近的元素

01:查找最接近的元素

总时间限制: 
1000ms
内存限制: 
65536kB
描述

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

输入
第一行包含一个整数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


















#include<stdio.h>
#include<queue>
#include<math.h>
#include<string.h>
#include<iostream>
#include<stdlib.h>
#include<algorithm>
using namespace std;
int n,m,target;
int base,top,mid=0;
long long nums[100010];
int main(){
	memset(nums,-1,sizeof(nums));
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>nums[i];
	}
	cin>>m;
	while(m--){
		cin>>target;
		base=0;
		top=n-1;
		while(base<=top){
			mid=(base+top)/2;
			if(nums[mid]==target){
				break;;
			}else if(nums[mid]<target){
				base=mid+1;
			}else {
				top=mid-1;
			}
		}
		if(nums[mid]==target){
			cout<<target<<endl;
		}else{
			if(base>=n||base<0){
				cout<<nums[top]<<endl;
			}else if(top>=n||top<0){
				cout<<nums[base]<<endl;
			}else{
				if(abs(nums[base]-target)>abs(nums[top]-target)){
					cout<<nums[top]<<endl;
				}else{
					if(abs(nums[base]-target)<abs(nums[top]-target)){
						cout<<nums[base]<<endl;
					}else{
						if(base<top){
							cout<<nums[base]<<endl;
						}else{
							cout<<nums[top]<<endl;
						}
					}
				}
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_33837704/article/details/80314377