#hi does anyone know a great way of
1 messages · Page 1 of 1 (latest)
it's iterating frequencies backwards
so it's starting with the highest frequencies and going through all (unique) array elements that have this frequency
and it adds these to the result list
and if at any point len(result) == k is true it exits
@pearl trench
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# O(n)
c = Counter(nums)
# O(n log k)
hq = []
for i,j in c.items():
heappush(hq, (j, i))
if len(hq) > k:
heappop(hq)
# O(k)
return list(map(lambda e: e[1], hq))
here's a solution I came up with