LeetCode/주제별 보충

Heap-PrioiryQueue: 973. K Closest Points to Origin ★

hyunkookim 2025. 1. 20. 14:47

973. K Closest Points to Origin

 

https://youtu.be/rI2EBUEMfTk?si=rQzq5oqyjL2M1qgb

 

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        # k번째 가까운 points 리턴,
        # [distance, x, y] 로 저장
        # minHeap 사용
        minHeap = []

        for x, y in points:
            dist = (x**2) + (y**2)
            minHeap.append([dist, x, y])

        heapq.heapify(minHeap)

        res = []
        while k > 0:        
            dist, x, y = heapq.heappop(minHeap)
            res.append([x, y])
            k -=1

        return res