先简单贴个题解,有空再补充0.0
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int ax = 0;
vector<int> res(k);
int m = abs(arr[0] - x);
for (int i = 0; i < arr.size(); i++) {
if (abs(arr[i] - x) < m) {
m = abs(arr[i] - x);
ax = i;
}
}
int num = 1;
int left = ax - 1;
int right = ax + 1;
while (num < k) {
if (left < 0) {
right += k - num;
break;
}
if (right >= arr.size()) {
left -= k - num;
break;
}
while (num < k && left >= 0 && right < arr.size() &&
x - arr[left] <= arr[right] - x) {
left--;
num++;
}
while (num < k && left >= 0 && right < arr.size() &&
x - arr[left] > arr[right] - x) {
right++;
num++;
}
}
int j = 0;
for (int i = left + 1; i < right; i++) {
res[j++] = arr[i];
}
return res;
}
};