문제 링크: https://leetcode.com/problems/k-closest-points-to-origin/description/
파이썬 소스: https://bit.ly/49icv0X
이번 문제도 heapq를 사용해서 풀 수 있습니다.
from typing import List
import heapq
class Solution:
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
heap = []
for x, y in points:
distance = x*x + y*y
if len(heap) == k:
heapq.heappushpop(heap, (-distance, x, y))
else:
heapq.heappush(heap, (-distance, x, y))
return [[x, y] for dist, x, y in heap]
댓글 없음:
댓글 쓰기