zoukankan      html  css  js  c++  java
  • Top K Frequent Words

    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
  • 相关阅读:
    javascript类继承系列一
    Update Statistics用法
    FOR XML PATH
    SQL Server 中WITH (NOLOCK)
    ROW_NUMBER () 与 PARTITION组合拳
    sql脚本的格式
    存储过程
    动态sql
    尽量不要用select into 复制表
    杂谈
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5595221.html
Copyright © 2011-2022 走看看