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
  • 相关阅读:
    ejs
    appcan.slider.js探索
    js语法重点
    canvas动画
    canvas绘图
    Bootstrap 表单
    模态框
    Node.js EventEmitter(事件队列)
    Node.js 事件循环
    react native 页面跳转
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5595221.html
Copyright © 2011-2022 走看看