Advertisement
smj007

Untitled

Mar 10th, 2024
855
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.51 KB | None | 0 0
  1. class Solution:
  2.     def topKFrequent(self, nums: List[int], k: int) -> List[int]:
  3.  
  4.         # build a heap
  5.         hashmap = defaultdict(int)
  6.         maxheap = []
  7.         for num in nums:
  8.             hashmap[num] += 1
  9.  
  10.         for num, count in hashmap.items():
  11.             heapq.heappush(maxheap, (-count, num))
  12.  
  13.         result = []
  14.         for _ in range(k):
  15.             if maxheap:
  16.                 top, val = heapq.heappop(maxheap)
  17.                 result.append(val)
  18.  
  19.         return result
  20.  
  21.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement