Skip to content

Commit fd78535

Browse files
committed
Sync LeetCode submission Runtime - 47 ms (90.56%), Memory - 22.2 MB (33.09%)
1 parent 1ea82bc commit fd78535

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
<p>Given an array of <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents a point on the <strong>X-Y</strong> plane and an integer <code>k</code>, return the <code>k</code> closest points to the origin <code>(0, 0)</code>.</p>
2+
3+
<p>The distance between two points on the <strong>X-Y</strong> plane is the Euclidean distance (i.e., <code>&radic;(x<sub>1</sub> - x<sub>2</sub>)<sup>2</sup> + (y<sub>1</sub> - y<sub>2</sub>)<sup>2</sup></code>).</p>
4+
5+
<p>You may return the answer in <strong>any order</strong>. The answer is <strong>guaranteed</strong> to be <strong>unique</strong> (except for the order that it is in).</p>
6+
7+
<p>&nbsp;</p>
8+
<p><strong class="example">Example 1:</strong></p>
9+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" style="width: 400px; height: 400px;" />
10+
<pre>
11+
<strong>Input:</strong> points = [[1,3],[-2,2]], k = 1
12+
<strong>Output:</strong> [[-2,2]]
13+
<strong>Explanation:</strong>
14+
The distance between (1, 3) and the origin is sqrt(10).
15+
The distance between (-2, 2) and the origin is sqrt(8).
16+
Since sqrt(8) &lt; sqrt(10), (-2, 2) is closer to the origin.
17+
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
18+
</pre>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
22+
<pre>
23+
<strong>Input:</strong> points = [[3,3],[5,-1],[-2,4]], k = 2
24+
<strong>Output:</strong> [[3,3],[-2,4]]
25+
<strong>Explanation:</strong> The answer [[-2,4],[3,3]] would also be accepted.
26+
</pre>
27+
28+
<p>&nbsp;</p>
29+
<p><strong>Constraints:</strong></p>
30+
31+
<ul>
32+
<li><code>1 &lt;= k &lt;= points.length &lt;= 10<sup>4</sup></code></li>
33+
<li><code>-10<sup>4</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
34+
</ul>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Approach 2: Max Heap
2+
3+
# Time: O(n * log k)
4+
# Space: O(k)
5+
6+
import heapq
7+
8+
class Solution:
9+
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
10+
heap = [(-self.squared_distance(points[i]), i) for i in range(k)]
11+
heapq.heapify(heap)
12+
13+
for i in range(k, len(points)):
14+
dist = -self.squared_distance(points[i])
15+
if dist > heap[0][0]:
16+
heapq.heappushpop(heap, (dist, i))
17+
18+
return [points[i] for (_, i) in heap]
19+
20+
21+
def squared_distance(self, point):
22+
return point[0] ** 2 + point[1] ** 2
23+

0 commit comments

Comments
 (0)