def topKFrequent(self, words, k):
count = collections.Counter(words)
heap = [(-freq, word) for word, freq in count.items()]
heapq.heapify(heap)
return [heapq.heappop(heap)[1] for _ in xrange(k)]
当我为它提供一个字符串数组时["aa", "aaa", "a"]
,1
它会正确返回["a"]
. 我的问题是堆是否也在内部按字典顺序对元组进行排序?因为根据我的说法,如果没有排序,它会简单地返回["aa"]
(构建堆的顺序,因为所有三个的计数都是相同的)。还是我误解了heapq
?