- class Solution:
- def topKFrequent(self,nums:List[int],k:int)->List[int]:
- counter={}
- for n in nums:
- counter.setdefault(n,0)
- counter[n]+=1
- num_count = [(-v,k) for k,v in counter.items()]
- import heapq
- heapq.heapify(num_count)
- res= []
- for _ in range(k):
- res.append(heapq.heappop(num_count)[1])
- return res
- class Solution:
- def topKFrequent(self,nums:List[int],k:int) ->List[int]:
- counter ={}
- for n in nums:
- counter.setdefault(n,0)
- counter[n]+=1
- num_count = [(-v,k) for k,v in counter.items()]
- import heapq
- heap.heapify(num_count)
- res =[]
-
- for _ in range(k):
- res.append(heapq.heapop(num_count)[1])
- return res