这篇文章是程序自动发表的,详情可以见
这里
href="http://ounix1xcw.bkt.clouddn.com/github.markdown.css" rel="stylesheet">
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

本文介绍LeetCode上第692题Top K Frequent Words的解决思路及实现代码,采用二叉堆进行堆排序,确保返回的单词按频率从高到低排序,并在频率相同时按字母顺序排列。

424

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



