在做leetcode 347. 前 K 个高频元素 时候,使用heapq是遇到该问题
原因在于:
我的代码是:
heap = heapq.heapify([(-count, w) for w, count in dic.items()])
return [heapq.heappop(heap)[1] for _ in range(k)]
正确代码应该是:
heap = [(-count, w) for w, count in dic.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in range(k)]
区别在于,heapify需要给定参数,并且无返回值。