Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution:
- def topKFrequent(self, nums: List[int], k: int) -> List[int]:
- # build a heap
- hashmap = defaultdict(int)
- maxheap = []
- for num in nums:
- hashmap[num] += 1
- for num, count in hashmap.items():
- heapq.heappush(maxheap, (-count, num))
- result = []
- for _ in range(k):
- if maxheap:
- top, val = heapq.heappop(maxheap)
- result.append(val)
- return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement