码迷,mamicode.com
首页 > 其他好文 > 详细

Top K Frequent Words

时间:2016-06-17 22:25:01      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

Given a list of words and an integer k, return the top k frequent words in the list.

Given

[
    "yes", "lint", "code",
    "yes", "code", "baby",
    "you", "baby", "chrome",
    "safari", "lint", "code",
    "body", "lint", "code"
]

for k = 3, return ["code", "lint", "baby"].

for k = 4, return ["code", "lint", "baby", "yes"],

You should order the words by the frequency of them in the return list, the most frequent one comes first. If two words has the same frequency, the one with lower alphabetical order come first.

这题是代码思路还是很明确的,先利用dict,统计每个字符出现的次数,之后进行排序,取前k个。但是注意提示中写的,两个单词出现频次相同时,按照词典序让比较小的排在前面。所以实际在写的时候,需要不仅靠频次排序,也需要靠词本身排序。代码如下:

class Solution:
    # @param {string[]} words a list of string
    # @param {int} k an integer
    # @return {string[]} a list of string
    def topKFrequentWords(self, words, k):
        map = {}
        for w in words:
            if w not in map:
                map[w] = 1
            else:
                map[w] += 1
        import heapq
        heap = []
        for key, value in map.iteritems():
            heapq.heappush(heap,(0-value,key))
        
        res = [w[1] for w in heapq.nsmallest(k,heap,key = lambda x: (x[0],x[1]))]
        return res

 

Top K Frequent Words

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5595221.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!