-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathFindKClosestElements.cpp
More file actions
56 lines (47 loc) · 1.21 KB
/
Copy pathFindKClosestElements.cpp
File metadata and controls
56 lines (47 loc) · 1.21 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
int ls(vector<int>& arr, int start, int end, int key){
while(start <= end){
if(arr[start] > key){
break;
}
start++;
}
if(start > 0){
return start-1;
}
return 0;
}
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int n = arr.size();
int index = ls(arr, 0, n-1, x);
cout << "index : " << index << endl;
int i = index-1, j = index, st = index, end = index;
while(k){
if(i >= 0 && j < n){
if(abs(arr[i]-x) > abs(arr[j]-x)){
end = j;
j++;
}
else{
st = i;
i--;
}
}
else if(i >= 0){
st = i;
i--;
}
else{
end = j;
j++;
}
k--;
}
vector<int> sol;
for(int i = st; i <= end; i++){
sol.push_back(arr[i]);
}
return sol;
}
};