href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
这是leetcode的第692题--Top K Frequent Words
题目 Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first. 思路 用map就很简单。但这道题是考堆排序的,所以我写了个二叉堆来排序。
show me the code
class Solution: def topKFrequent(self, words, k): """ :type words: List[str] :type k: int :rtype: List[str] """ hp = binaryHeap(sortByFrequency = True,reverse=True) for i in words: hp.insert(i) rst = [] n = len(hp) for i in hp.data: print(i.val,i.freq) mp = {} while hp: top = hp.deleteTop() if top.freq in mp: mp[top.freq].append(top.val) else: mp[top.freq] = [top.val] for i in mp: mp[i].sort() key = sorted(mp.keys(),reverse = True) count = 0 for i in key: for j in mp[i]: rst.append(j) count =1 if count == k:return rst
1575



被折叠的 条评论
为什么被折叠?



