-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindClosestElements.cpp
More file actions
39 lines (34 loc) · 866 Bytes
/
findClosestElements.cpp
File metadata and controls
39 lines (34 loc) · 866 Bytes
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
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
if(arr.size() <= k)
return arr;
int fast = 0;
vector<int> res(k, 0);
while(fast < arr.size() && arr[fast] < x){
++fast;
}
int left = fast, right = fast, i = 0;
while(res.size() < k){
if(left < 0){
res[i++] = arr[right];
continue;
}else if(right > arr.size()){
res[i++] = arr[left];
continue;
}
if(abs(arr[left] - x) <= abs(arr[right] - x)){
res[i++] = arr[left];
}else{
res[i++] = arr[right];
}
}
return res;
}
};
int main(){
return 0;
}