728x90
https://leetcode.com/problems/k-closest-points-to-origin/
K Closest Points to Origin - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제) 평면상에 points 목록이 있을 때, 원점 (0, 0)에서 k번 가까운 점 목록을 순서대로 출력하라. 평면상 두 점의 거리는 유클리드 거리로 한다.
풀이)
import heapq
import math
def cal_dist(point):
return math.sqrt(point[0] * point[0] + point[1] * point[1])
def k_closest_builtin(points, k):
dists = []
heap = []
for point in points:
dist = cal_dist(point)
heapq.heappush(heap, dist)
dists.append(dist)
kth_dist = [heapq.heappop(heap) for _ in range(k)][-1]
return [points[idx] for idx, dist in enumerate(dists) if dist <= kth_dist]
print(k_closest_builtin([[3,3],[5,1],[-2,4]], 2))
728x90
'알고리즘 > 파이썬' 카테고리의 다른 글
[파이썬 알고리즘] 이코테 - 부품찾기 (0) | 2022.05.28 |
---|---|
[파이썬 알고리즘] 75.leetcode - Sort Colors (0) | 2022.05.27 |
[파이썬 알고리즘] Mergesort 기초. (0) | 2022.05.27 |
[파이썬 알고리즘] Quicksort(퀵정렬) 기초. (0) | 2022.05.27 |
[파이썬 알고리즘] 정렬 기초(1) (2) | 2022.05.26 |