Problem : https://leetcode.com/problems/top-k-frequent-elements/
Use hash map to save count of each elements.
Then use heap to get first k element .
Time Complexity = O ( N Log k )
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
if k > len(nums): return nums
count = Counter(nums)
return heapq.nlargest(k, count.keys(), key=count.get)
No comments:
Post a Comment