973. K Closest Points to Origin

https://leetcode.com/problems/k-closest-points-to-origin/

Array sort

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

Priority Queue (Heapq in python3)

import heapq
class Solution:
    def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:
        return heapq.nsmallest(K,points,key=lambda x:x[0]**2+x[1]**2)
        

heapq.nsmallest(Number, Iterable, Key)

Last updated

Was this helpful?