-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path658. Find K Closest Elements.cpp
46 lines (44 loc) · 1.45 KB
/
658. Find K Closest Elements.cpp
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
38
39
40
41
42
43
44
45
46
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
auto it = lower_bound(arr.begin(), arr.end(), x);
int left, right;
// First we find the closest element, initialize both left and right to that closest element's index, then increment left or right from there
if (it == arr.end()) { // Test for Edge cases
right = arr.size() - 1;
left = arr.size() - k;
return vector<int> (arr.begin() + left, arr.begin() + right + 1);
}
if (it == arr.begin()) {
right = k - 1;
left = 0;
return vector<int> (arr.begin() + left, arr.begin() + right + 1);
}
if (x - *(it - 1) <= *it - x) {
left = it - 1 - arr.begin();
right = left;
}
else {
left = it - arr.begin();
right = left;
}
// Main loop starts here
while (right - left + 1 < k) {
if (left == 0) {
right = k - 1;
break;
}
else if (right == arr.size() - 1) {
left = arr.size() - k;
break;
}
if (x - arr[left - 1] <= arr[right + 1] - x) {
left --;
}
else {
right ++;
}
}
return vector<int> (arr.begin() + left, arr.begin() + right + 1);
}
};