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