题意:返回的是高频元素的值 nums = [1,1,1,2,2,3], k = 2输出[1,2],1,2这两个元素频率最高
前k个大的小的,第k个大的小的 ,都用大根堆小根堆来做。相对于排序,时间复杂度更低
利用heapq小根堆的包
import heapq
class Solution:
def topKFrequent(self,nums,k):
heap_max=[]
result=[]
dic = collections.defaultdict(int)
for num in nums:
dic[num] +=1
for i in dic: #i 是字典的key
heapq.heappush(heap_max,(-dic[i],i))#小根堆作为大根堆,其实仍是小根堆,只不过最小值的相反数是最大值
for j in range(k):
result.append(heapq.heappop(heap_max)[-1])
return result
collections.Counter()
a = [1,1,3,4,3] b=Counter(a) b={1:2,3:2,4:1} key是a的值, value是统计次数
返回前k个元素,这时候可以应用Counter的一个函数,most_common(k),但是返回的形式是一个元祖列表,类似[(1,2),(3,2),(4,1)]的形式
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return [i[0] for i in Counter(nums).most_common(k)]