任务是返回K最频繁的元素。我所做的就是计算频率,并把它放在一个最小堆(我们知道在Python中没有最大堆),然后我需要heappop k次。
from collections import defaultdict
import heapq
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
counts = defaultdict(int)
for i in range(len(nums)):
counts[nums[i]] -= 1
counts = list(counts.items())
heapq.heapify(counts)
top_k = [heapq.heappop(counts)[0] for i in range(k)]
return top_k为什么我的代码在topKFrequent([4,1,-1,2,-1,2,3], 2)上失败
发布于 2022-08-28 13:43:03
你问它为什么失败。它失败了,因为堆弹正在从计数中返回最小的项。计数是元组,所以它是元组的第一个元素最小的元组,也就是num。所以你要拿回名词,但只有唯一的,因为字典本质上就像一本集。
https://stackoverflow.com/questions/73518885
复制相似问题