Skip to content

Commit 65cedc3

Browse files
Add 'K Closest Points to Origin'
1 parent 2ebfc69 commit 65cedc3

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ A collection of LeetCode solutions
2020

2121
[Invert Binary Tree](./src/invert_binary_tree.py)
2222

23+
[K Closest Points to Origin](./src/k_closest_points_to_origin.py)
24+
2325
[Linked List Cycle](./src/linked_list_cycle.py)
2426

2527
[Longest Common Subsequence](./src/longest_common_subsequence.py)

src/k_closest_points_to_origin.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
973. K Closest Points to Origin
3+
4+
https://leetcode.com/problems/k-closest-points-to-origin
5+
6+
NOTES
7+
* I call it house work, 'cause it's light work. Calculate distance,
8+
maintain max-heap (closest distance is equivalent to smallest distance) of
9+
k points.
10+
"""
11+
12+
import heapq
13+
import math
14+
15+
16+
class Solution:
17+
"""
18+
Maintains a max-heap of size k containing the k closest points to the
19+
origin. Since the `heapq` module only provides an implementation for a min-
20+
heap, the distance is negated before being inserted into the heap.
21+
"""
22+
def kClosest(self, points: list[list[int]], k: int) -> list[list[int]]:
23+
24+
heap: list[tuple[float, list[int]]] = [] # (distance, [xi,yi])
25+
26+
for i, p in enumerate(points):
27+
d = math.sqrt(p[0]**2 + p[1]**2)
28+
if i < k:
29+
heapq.heappush(heap, (-d, p))
30+
else:
31+
if -d > heap[0][0]:
32+
heapq.heapreplace(heap, (-d, p))
33+
34+
return [p[1] for p in heap]
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
973. K Closest Points to Origin
3+
4+
https://leetcode.com/problems/k-closest-points-to-origin
5+
"""
6+
7+
from unittest import TestCase
8+
9+
from src.k_closest_points_to_origin import Solution
10+
11+
12+
class TestSolution(TestCase):
13+
def test_1(self):
14+
exp = sorted([[-2, 2]])
15+
assert sorted(Solution().kClosest([[1, 3], [-2, 2]], 1)) == exp
16+
17+
def test_2(self):
18+
exp = sorted([[3, 3], [-2, 4]])
19+
assert sorted(Solution().kClosest([[3, 3], [5, -1], [-2, 4]], 2)) == exp

0 commit comments

Comments
 (0)