Skip to content

Latest commit

 

History

History
30 lines (21 loc) · 550 Bytes

347.md

File metadata and controls

30 lines (21 loc) · 550 Bytes

[347] Top K Frequent Elements

Description

link


Solution : Sliding Windows

  • See Code

Code

Complexity T : O( n + nlogk )

# O(n) + O(nlogk)
class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:
        cnt = collections.Counter(nums)
        q = []
        for i, v in cnt.items():
            heapq.heappush(q, (v, i))
            if len(q) > k:
                heapq.heappop(q)
        return [n for _, n  in q]