Skip to content

Commit e32d33e

Browse files
authored
Create kclosestelements.cpp
Added solution for this problem
1 parent 6c026ee commit e32d33e

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

kclosestelements.cpp

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public:
3+
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
4+
int left = 0;
5+
int right = arr.size() - k;
6+
7+
while(left < right){
8+
int mid = (left + right) / 2;
9+
if(x-arr[mid] > arr[mid+k]-x){
10+
left = mid + 1;
11+
}else {
12+
right = mid;
13+
}
14+
}
15+
return vector<int>(arr.begin()+left, arr.begin()+left+k);
16+
}
17+
};

0 commit comments

Comments
 (0)