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

 

+ Recent posts