zoukankan      html  css  js  c++  java
  • 471. 最高频的K个单词

    471. 最高频的K个单词

    中文English

    给一个单词列表,求出这个列表中出现频次最高的K个单词。

    样例

    样例 1:

    输入:
      [
        "yes", "lint", "code",
        "yes", "code", "baby",
        "you", "baby", "chrome",
        "safari", "lint", "code",
        "body", "lint", "code"
      ]
      k = 3
    输出: ["code", "lint", "baby"]
    

    样例 2:

    输入:
      [
        "yes", "lint", "code",
        "yes", "code", "baby",
        "you", "baby", "chrome",
        "safari", "lint", "code",
        "body", "lint", "code"
      ]
      k = 4
    输出: ["code", "lint", "baby", "yes"] 
    

    挑战

    用 O(n log k)的时间和 O(n) 的额外空间完成。

    注意事项

    你需要按照单词的词频排序后输出,越高频的词排在越前面。如果两个单词出现的次数相同,则词典序小的排在前面。

     
     
    输入测试数据 (每行一个参数)如何理解测试数据?
    class Solution:
        """
        @param words: an array of string
        @param k: An integer
        @return: an array of string
        """
        """
        大致思路:
        1.初始化dic,求得所有单词出现的次数,然后根据词典序进行排列,最后返回前K个即可
        """
        def topKFrequentWords(self, words, k):
            # write your code here
            #初始化
            dic = {}
            sort_list = []
            res = []
            
         #首先先根据词典序排好序,逆序 words
    = sorted(words)[:: -1] for word in words: dic[word] = dic.get(word, 0) + 1
        
        #根据dic的key和value进行append
        for key,value in dic.items(): sort_list.append([key, value]) sort_list = sorted(sort_list, key = lambda A: A[1])[:: -1] return [_[0] for _ in sort_list[: k]]
  • 相关阅读:
    Linux常用几种shell
    opencv中snake的调用方法示例
    GIT 常用命令手册
    偏最小二乘法回归(Partial Least Squares Regression)
    镜头的参数指标
    Git详解Git分支
    tab选项卡,不带自动切换定时器
    setTimeout和setInterval
    tab选项卡,带自动播放
    动态添加,删除class样式
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13149977.html
Copyright © 2011-2022 走看看