Skip to content

Commit 8227ca6

Browse files
Create kth_closest_point_to_origin.cpp
1 parent 3f08af5 commit 8227ca6

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

kth_closest_point_to_origin.cpp

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
3+
struct Comp {
4+
bool operator()(const pair<int, int> &p1, const pair<int, int> &p2) {
5+
int distance1 = p1.first*p1.first + p1.second*p1.second;
6+
int distance2 = p2.first*p2.first + p2.second*p2.second;
7+
return distance1 < distance2;
8+
}
9+
};
10+
11+
public:
12+
vector<vector<int>> kClosest(vector<vector<int>>& points, int k) {
13+
14+
priority_queue<pair<int, int>, vector<pair<int, int>>, Comp> maxHeap;
15+
16+
for(auto &point : points) {
17+
maxHeap.push({point[0], point[1]});
18+
if(maxHeap.size() > k) maxHeap.pop();
19+
}
20+
21+
vector<vector<int>> result;
22+
while(!maxHeap.empty()) {
23+
auto top = maxHeap.top();
24+
result.push_back({top.first, top.second});
25+
maxHeap.pop();
26+
}
27+
return result;
28+
}
29+
};

0 commit comments

Comments
 (0)