Advertisement
aero2146

Top K Frequent Elements

Apr 10th, 2020
571
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.36 KB | None | 0 0
  1. class Solution:
  2.     def topKFrequent(self, nums: List[int], k: int) -> List[int]:
  3.         freq = collections.defaultdict(int)
  4.         heap = []
  5.        
  6.         for num in nums:
  7.             freq[num] += 1
  8.        
  9.         for key, val in freq.items():
  10.             heapq.heappush(heap, (val, key))
  11.        
  12.         return [x[1] for x in heapq.nlargest(k, heap)]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement