forked from Ashish-kumar7/geeks-for-geeks-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLucy's Neighbours.cpp
More file actions
39 lines (26 loc) · 834 Bytes
/
Lucy's Neighbours.cpp
File metadata and controls
39 lines (26 loc) · 834 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
class Solution{
static bool comp(pair<int,int>p1,pair<int,int>p2){
if(p1.first==p2.first)return p1.second < p2.second;
return p1.first<p2.first;
}
public:
vector<int> Kclosest(vector<int>arr, int n, int x, int k)
{
// Your code goes here
vector<pair<int,int>>vec;
for(int i=0;i<n;i++){
vec.push_back({abs(arr[i]-x),arr[i]});
}
sort(vec.begin(),vec.end(),comp);
vector<int>ans;
int count=0;
for(int i=0;i<vec.size();i++){
if(count < k){
count++;
ans.push_back(vec[i].second);
}
}
sort(ans.begin(),ans.end());
return ans;
}
};