[LeetCode] Find K Closest Elements

658. Find K Closest Elements

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a < b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int r = lower_bound(begin(arr), end(arr), x) - begin(arr), l = r - 1;
vector<int> res;
while(k--) {
if(l == -1) res.push_back(arr[r++]);
else if(r == arr.size()) res.push_back(arr[l--]);
else {
if(abs(arr[r] - x) < abs(arr[l] - x)) res.push_back(arr[r++]);
else res.push_back(arr[l--]);
}
}
sort(begin(res), end(res));
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/25/PS/LeetCode/find-k-closest-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.