Skip to content

Instantly share code, notes, and snippets.

@shortthirdman
Created May 17, 2022 12:27
Show Gist options
  • Save shortthirdman/506cc5abae8a21a66de7d9921441a84a to your computer and use it in GitHub Desktop.
Save shortthirdman/506cc5abae8a21a66de7d9921441a84a to your computer and use it in GitHub Desktop.
Finding the top K frequent elements from the array/list of integers
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