Created
May 17, 2022 12:27
-
-
Save shortthirdman/506cc5abae8a21a66de7d9921441a84a to your computer and use it in GitHub Desktop.
Finding the top K frequent elements from the array/list of integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from heapq import heappush, heappop | |
from collections import defaultdict | |
class Solution: | |
def topKFrequent(self, nums: List[int], k: int) -> List[int]: | |
if nums == []: | |
return [] | |
map = {} | |
for num in nums: | |
if num in map: | |
map[num] += 1 | |
else: | |
map[num] = 1 | |
maxx = 0 | |
heap = [] | |
for key,value in map.items(): | |
if len(heap) < k: | |
heappush(heap,[value,key]) | |
elif heap[0][0] < value: | |
heappop(heap) | |
heappush(heap,[value,key]) | |
return [item for count,item in heap[::-1]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment