二分查找和分治算法。
思路:有以下几种情况:1、当恰好存在与X等值的元素时,答案就是这一元素;2、当元素都大于X时,答案就是最小元素;3、当元素都小于X时,答案就是最大元素;4、当既有小于也有大于X的元素时,返回差的绝对值最小的。
代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
vector<int> a;
vector<int> b;
for (int i = 0; i < n; ++i)
{
int temp;
cin >> temp;
a.push_back(temp);
}
for (int i = 0; i < m; ++i)
{
int temp;
cin >> temp;
vector<int>::iterator it1 = lower_bound(a.begin(), a.end(), temp);
vector<int>::iterator it2 = upper_bound(a.begin(), a.end(), temp);
if (*it1 < *it2) b.push_back(*it1);
else b.push_back(*(it1 - 1));
}
vector<int>:: iterator it;
for(it = b.begin(); it != b.end(); ++it) cout << *it << endl;
}