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 b310a65

Browse files
K Closest Points to Origin
1 parent c063ec9 commit b310a65

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

‎973-k-closest-points-to-origin.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,27 @@
2929
-104 < xi, yi < 104
3030
"""
3131
import math
32+
import heap
3233

34+
35+
# Time Complexity: NLOGK
36+
class Solution:
37+
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
38+
heap = [(-self.getDistance(points[index]), index) for index in range(k)]
39+
40+
heapq.heapify(heap)
41+
42+
for index in range(k, len(points)):
43+
heapq.heappushpop(heap, (-self.getDistance(points[index]), index))
44+
45+
return [points[index] for _, index in heap]
46+
47+
def getDistance(self, point):
48+
x, y = point
49+
return math.sqrt((x**2) + (y**2))
50+
51+
52+
# Time Complexity: NLogN
3353
class Solution:
3454
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
3555
distance = []

0 commit comments

Comments
(0)

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