Skip to content

Commit 55fc622

Browse files
authored
Create find-k-closest-elements.cpp
1 parent 820b5aa commit 55fc622

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

C++/find-k-closest-elements.cpp

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
// Time: O(logn + k)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
7+
auto i = distance(arr.begin(), lower_bound(arr.begin(), arr.end(), x));
8+
int left = i - 1, right = i;
9+
while (k--) {
10+
(right >= arr.size() || (left >= 0 && abs(arr[left] - x) <= abs(arr[right] - x) )) ? --left : ++right;
11+
}
12+
return vector<int>(arr.begin() + left + 1, arr.begin() + right);
13+
}
14+
};

0 commit comments

Comments
 (0)