-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0658-find-k-closest-elements.cpp
More file actions
37 lines (36 loc) · 1.14 KB
/
Copy path0658-find-k-closest-elements.cpp
File metadata and controls
37 lines (36 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int dist(vector<int>& arr, int a, int b) {
return abs(a - b);
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
auto it = lower_bound(arr.begin(), arr.end(), x);
int left = it - arr.begin() - 1;
int right = it - arr.begin();
vector<int> result;
while (k--) {
if (left >= 0 && right < arr.size()) {
int dist_left = dist(arr, x, arr[left]);
int dist_right = dist(arr, x, arr[right]);
if (dist_left < dist_right || (dist_left == dist_right && arr[left] < arr[right])) {
result.push_back(arr[left]);
left--;
}
else {
result.push_back(arr[right]);
right++;
}
}
else if (left >= 0) {
result.push_back(arr[left]);
left--;
}
else {
result.push_back(arr[right]);
right++;
}
}
sort(result.begin(), result.end());
return result;
}
};