Skip to content
This repository was archived by the owner on Sep 22, 2021. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions LeetCode/0973_ K_Closest_Points_to_Origin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from heapq import heappop, heappush
from typing import List, Tuple


class Solution:
def closest_points(self, points: List[Tuple[float, float]], k: int) -> List[Tuple[float, float]]:
"""
Finds the K points closest to the origin.

The implementation pushes the points on a Heap with their key being the distance to the origin, then removes K elements from the heap.
I chose to go with a more verbose implementation to show how it can be done, but alternatively one could do:

>>> from heapq import nsmallest
... nsmallest(k, points, key=self.distance)
"""

heap = []
for point in points:
heappush(heap, (self.distance(point), point))

return [heappop(heap)[1] for _ in range(k)]

def distance(self, point: Tuple[float, float]) -> float:
"""
Pythagorean formula to get the distance to the origin.
"""

return (point[0] ** 2 + point[1] ** 2) ** 0.5