Faaez Razeen

K Closest Points to Origin

  • 1 min read
  • LC-Medium
  • Binary-heap

3 years ago

Solution

TimeSpaceExplanation
O(n)O(n)
def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]: distances = [] for x, y in points: dist = (x ** 2 + y ** 2) ** 0.5 distances.append((dist, (x, y))) heapify(distances) ans = [] while k: ans.append(heappop(distances)[1]) k -= 1 return ans