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

Sign up
Appearance settings

Commit 151d53a

Browse files
Merge pull request vJechsmayr#423 from MaryWeeb/patch-1
Added 0973 - K Closest Points to Origin
2 parents 7bf8566 + 8743a40 commit 151d53a

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
from heapq import heappop, heappush
2+
from typing import List, Tuple
3+
4+
5+
class Solution:
6+
def closest_points(self, points: List[Tuple[float, float]], k: int) -> List[Tuple[float, float]]:
7+
"""
8+
Finds the K points closest to the origin.
9+
10+
The implementation pushes the points on a Heap with their key being the distance to the origin, then removes K elements from the heap.
11+
I chose to go with a more verbose implementation to show how it can be done, but alternatively one could do:
12+
13+
>>> from heapq import nsmallest
14+
... nsmallest(k, points, key=self.distance)
15+
"""
16+
17+
heap = []
18+
for point in points:
19+
heappush(heap, (self.distance(point), point))
20+
21+
return [heappop(heap)[1] for _ in range(k)]
22+
23+
def distance(self, point: Tuple[float, float]) -> float:
24+
"""
25+
Pythagorean formula to get the distance to the origin.
26+
"""
27+
28+
return (point[0] ** 2 + point[1] ** 2) ** 0.5

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /