-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find k closest elements
48 lines (38 loc) · 1.03 KB
/
Find k closest elements
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
#include <bits/stdc++.h>
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int ind = lower_bound(arr.begin() , arr.end() , x) - arr.begin() ;
int a = ind - 1;
int b = ind ;
int reqn = k ;
vector <int> ans ;
\
while(reqn != 0 )
{
int option1 = 1e9 ;
int option2 = 1e9 ;
if( a >= 0)
{
option1 = abs(x - arr[a]) ;
}
if(b < arr.size())
{
option2 = abs(x - arr[b]) ;
}
cout << option1 << " " << option2 << endl;
if(option1 <= option2)
{
ans.push_back(arr[a ]) ;
a-- ;
}
else{
ans.push_back(arr[b ]) ;
b++ ;
}
reqn-- ;
}
sort(ans.begin(),ans.end()) ;
return ans ;
}
};