LeetCode 973. K Closest Points to Origin

개발공부를해보자·2025년 2월 24일

LeetCode

목록 보기
64/95

파이썬 알고리즘 인터뷰 64번(리트코드 973) K Closest Points to Origin
https://leetcode.com/problems/k-closest-points-to-origin/

나의 풀이

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        points.sort(key = lambda p: p[0]**2 + p[1]**2)
        return points[:k]

다른 풀이

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        heap = []

        for x, y in points:
            heapq.heappush(heap, (x**2 + y**2, x, y))
        
        result = []

        for _ in range(k):
            dist, x, y = heapq.heappop(heap)
            result.append([x, y])
        
        return result
profile
개발 공부하는 30대 비전공자 직장인

0개의 댓글