Advertisement
smj007

Untitled

Aug 17th, 2024
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. # Minheap: [O(N) + klogN ~ O(N) + N(logN) ~ NlogN, O(N)]
  2.  
  3. class Solution:
  4.     def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
  5.  
  6.         dist = [(math.sqrt(x**2 + y**2), x, y) for x, y in points]
  7.         heapq.heapify(dist) # O(N)
  8.  
  9.         res = []
  10.         for _ in range(k):
  11.             d, x, y = heapq.heappop(dist)
  12.             res.append([x, y]) # log N
  13.  
  14.         # O(N) + klogN ~ O(N) + N(logN) ~ NlogN
  15.         return res
  16.  
  17. # MaxHeap [O(Nlogk), O(k)]
  18.  
  19. class Solution:
  20.     def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
  21.  
  22.         dist = [(-math.sqrt(x**2 + y**2), x, y) for x, y in points[:k]]
  23.         heapq.heapify(dist) # O(k)
  24.  
  25.         for (x, y) in points[k:]:
  26.             distance = -math.sqrt(x**2 + y**2)
  27.             if distance > dist[0][0]:
  28.                 # what we are trying to do here is trying to have (N-k) farthest points
  29.                 # not in the heap; if any incoming point is farther than the farthest, we don't
  30.                 # do anything; if the incoming point is closer compared to farthest point in the heap
  31.                 # we remove the farthest point and add the incoming points; this ensure that we have
  32.                 # removed farthest of the farthest point of the point from the heap
  33.                 heappop(dist)
  34.                 heappush(dist, (distance, x, y)) # log(k)
  35.  
  36.         return [(x, y) for (_, x, y) in dist]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement