Skip to content

Commit 9d5adab

Browse files
authored
Merge pull request #1 from dmschauer/leet/973
solution for 973. K Closest Points to Origin
2 parents 4c8b8d4 + ab3c44b commit 9d5adab

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import heapq
2+
3+
class Solution:
4+
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
5+
minHeap = []
6+
7+
for x,y in points:
8+
minHeap.append([x**2 + y**2, x ,y]) # no need for sqrt for comparing distances
9+
10+
# sorts elements in dist by first index (calculated distance)
11+
heapq.heapify(minHeap)
12+
13+
result = []
14+
15+
for i in range(0,k):
16+
d, x, y = heapq.heappop(minHeap)
17+
result.append([x,y])
18+
19+
return result
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import math
2+
3+
class Solution:
4+
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
5+
6+
dist = []
7+
8+
for i in range(0,len(points)):
9+
dist.append(math.sqrt(points[i][0]**2 + points[i][1]**2))
10+
11+
dist_sorted = dist.copy()
12+
dist_sorted.sort()
13+
max_dist = dist_sorted[k-1]
14+
15+
result = []
16+
for i in range(0,len(points)):
17+
if(dist[i] <= max_dist):
18+
result.append(points[i])
19+
20+
return result

0 commit comments

Comments
 (0)