Skip to content

Commit 59a404d

Browse files
Create k_closest_elements.cpp
1 parent d4688ca commit 59a404d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

k_closest_elements.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
struct Comp {
3+
bool operator()(const pair<int, int> &p1, const pair<int, int> &p2) {
4+
if(p1.first != p2.first) {
5+
return p1.first < p2.first;
6+
}
7+
else
8+
return p1.second < p2.second;
9+
};
10+
};
11+
public:
12+
13+
//this works but it is not the most optimal
14+
//TC: O(k * log k) | SC: O(k)
15+
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
16+
17+
priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> maxHeap;
18+
19+
for(auto &num : arr) {
20+
int distance = abs(num - x);
21+
maxHeap.emplace(distance, num);
22+
if(maxHeap.size() > k) {
23+
maxHeap.pop();
24+
}
25+
}
26+
27+
vector<int> result;
28+
while(k-- and !maxHeap.empty()) {
29+
auto &[_, element] = maxHeap.top();
30+
result.emplace_back(element);
31+
maxHeap.pop();
32+
}
33+
34+
sort(result.begin(), result.end());
35+
return result;
36+
}
37+
};

0 commit comments

Comments
 (0)