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
풀이 과정
유클리드 거리가 가장 가까운 k개의 좌표를 출력하는 문제이다.
그냥 모든 좌표의 유클리드 거리를 구한 뒤, 정렬해서 앞에서 k개를 출력하거나, 우선순위 큐에 넣어서 k개를 pop을 해주는 방법으로 문제를 해결할 수 있다.
소스 코드
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = []
for x, y in points:
dist = x ** 2 + y ** 2
heapq.heappush(heap, (dist, x, y))
answer = []
for _ in range(k):
dist, x, y = heapq.heappop(heap)
answer.append([x, y])
return answer
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 33. Search in Rotated Sorted Array [Python] (0) | 2022.11.10 |
---|---|
LeetCode - 704. Binary Search [Python] (0) | 2022.11.02 |
LeetCode - 179. Largest Number [Python] (0) | 2022.10.20 |
LeetCode - 56. Merge Intervals [Python] (0) | 2022.10.17 |
LeetCode - 148. Sort List [Python] (0) | 2022.10.17 |