我有两个代码解决了同样的问题。但由于某种原因,一个比另一个快。我有一个问题,因为一个网格的速度是多少。
慢程序代码
#include <iostream>
#include <vector>
using namespace std;
int closeNumber(vector<int> N, int number, int size) {
int l = 0;
int r = size - 1;
while (r - l > 1) {
int mid = (l + r) / 2;
if (number > N[mid]) {
l = mid;
}
else {
r = mid;
}
}
if (N[r] - number < number - N[l]) {
return N[r];
}
return N[l];
}
int main()
{
int n, k;
cin >> n >> k;
vector<int> N(n);
vector<int> K(k);
for (int i = 0; i < n; i++) cin >> N[i];
int number;
for (int i = 0; i < k; i++) {
cin >> number;
cout << closeNumber(N, number, n) << endl;
}
return 0;
}
快速程序代码
#include <iostream>
using namespace std;
int main()
{
int n, k, x;
cin >> n >> k;
int arr[100000];
for (int i = 0; i < n; i++)
cin >> arr[i];
for (int h = 0; h < k; h++)
{
cin >> x;
int L = 0;
int R = n - 1;
while (R - L > 1)
{
int M = (R + L) / 2;
if (arr[M] < x)
L = M;
else
R = M;
}
if (x - arr[L] <= arr[R] - x) cout << arr[L] << endl;
else cout << arr[R] << endl;
}
return 0;
}