Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 63ba417

Browse filesBrowse files
Add files via upload
1 parent cfdceb1 commit 63ba417
Copy full SHA for 63ba417

File tree

1 file changed

+57
-0
lines changed
Filter options

1 file changed

+57
-0
lines changed
+57Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// 依然是使用堆排序的思想
2+
// Runtime: 240 ms, faster than 68.34% of C++ online submissions for K Closest Points to Origin.
3+
// Memory Usage: 45 MB, less than 60.94% of C++ online submissions for K Closest Points to Origin.
4+
5+
struct cell
6+
{
7+
cell (int x, int y, double d) : x(x), y(y), dis(d) {}
8+
9+
int x, y;
10+
double dis;
11+
};
12+
13+
class Solution
14+
{
15+
public:
16+
vector<vector<int>> kClosest(vector<vector<int>>& points, int k)
17+
{
18+
vector<vector<int>> res;
19+
20+
vector<cell> heap;
21+
for (int i = 0; i < k; ++i)
22+
{
23+
heap.push_back(cell(points[i][0], points[i][1], getdis(points[i][0], points[i][1])));
24+
}
25+
26+
make_heap(heap.begin(), heap.end(), key);
27+
28+
for (int i = k; i < points.size(); ++i)
29+
{
30+
if (heap[0].dis > getdis(points[i][0], points[i][1]))
31+
{
32+
pop_heap(heap.begin(), heap.end(), key);
33+
heap.pop_back();
34+
35+
heap.push_back(cell(points[i][0], points[i][1], getdis(points[i][0], points[i][1])));
36+
push_heap(heap.begin(), heap.end(), key);
37+
}
38+
}
39+
40+
for (auto item : heap)
41+
{
42+
vector<int> temp(2, 0);
43+
temp[0] = item.x;
44+
temp[1] = item.y;
45+
res.push_back(temp);
46+
}
47+
48+
return res;
49+
}
50+
private:
51+
bool(*key)(const cell&, const cell&) = [](const cell& pos1, const cell& pos2){return pos1.dis < pos2.dis; };
52+
private:
53+
double getdis(int x, int y)
54+
{
55+
return (x * x) + (y * y);
56+
}
57+
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.