当前位置: 首页 > news >正文

出现次数最多的k个数 Top K Frequent Words

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

问题:

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.

Example 1:

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order.

Example 2:

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively.

Note:

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters.

Follow up:

  1. Try to solve it in O(n log k) time and O(n) extra space.

解决:

①  用map,建立每个单词和其出现次数的映射,然后借助PriorityQueue进行自定义的排序,

class Solution {//108ms
    public List<String> topKFrequent(String[] words, int k) {
        List<String> res = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();//单词与出现次数的映射
        for (String word : words){
            map.put(word,map.getOrDefault(word,0) + 1);
        }
        PriorityQueue<Map.Entry<String,Integer>> priorityQueue =
                new PriorityQueue<>((a,b) -> (a.getValue() == b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue() - b.getValue()));//首先将单词按照出现次数由大到小排序,如果次数相同,则按字典序排序

        for (Map.Entry<String,Integer> entry : map.entrySet()){
            priorityQueue.offer(entry);
            if (priorityQueue.size() > k){
                priorityQueue.poll();
            }
        }
        while (! priorityQueue.isEmpty()){
            res.add(0,priorityQueue.poll().getKey());
        }
        return res;
    }
}

② 根据单词出现的次数进行桶排序。

class Solution { //24ms
    public List<String> topKFrequent(String[] words, int k) {
        List<String> res = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();
        List<String>[] bucket = new List[words.length + 1];
        for (String word : words){
            map.put(word,map.getOrDefault(word,0) + 1);
        }
        for (String key : map.keySet()){
            int count = map.get(key);
            if (bucket[count] == null){
                bucket[count] = new ArrayList<>();
            }
            bucket[count].add(key);
        }
        for (int j = bucket.length - 1;j >= 0 && res.size() < k;j --){
            if (bucket[j] != null){
                Collections.sort(bucket[j]);
                res.addAll(bucket[j]);
            }
        }
        return res.subList(0,k);//
    }
}

转载于:https://my.oschina.net/liyurong/blog/1607617

相关文章:

  • 异步拷贝文件
  • 用lua实现ByteArray和ByteArrayVarint
  • 作业2
  • 缓冲区溢出漏洞(2)
  • Visual Studio VS如何重置所有设置
  • Twirp:一个很酷的基于Go的新RPC框架
  • Nginx+Tomcat搭建高性能负载均衡集群
  • 我的第一篇博客
  • 我讲个事情哈,编程其实是文科
  • 基于Docker和Debian打造个人专属操作系统
  • thinkphp在前端页面的js代码中可以使用 U方法吗? 可以使用模板变量如__URL__等吗?...
  • 编写符合Python风格的对象
  • 二叉树基础之序列化和反序列化二叉树
  • 数组作业
  • Linux进程管理
  • 【Leetcode】101. 对称二叉树
  • bootstrap创建登录注册页面
  • canvas 绘制双线技巧
  • CoolViewPager:即刻刷新,自定义边缘效果颜色,双向自动循环,内置垂直切换效果,想要的都在这里...
  • C学习-枚举(九)
  • iOS小技巧之UIImagePickerController实现头像选择
  • node 版本过低
  • Spring Boot MyBatis配置多种数据库
  • Terraform入门 - 1. 安装Terraform
  • Vue 动态创建 component
  • 读懂package.json -- 依赖管理
  • 给新手的新浪微博 SDK 集成教程【一】
  • 每天10道Java面试题,跟我走,offer有!
  • 面试遇到的一些题
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 使用Maven插件构建SpringBoot项目,生成Docker镜像push到DockerHub上
  • 世界上最简单的无等待算法(getAndIncrement)
  • 系统认识JavaScript正则表达式
  • 学习ES6 变量的解构赋值
  • 译有关态射的一切
  • 阿里云服务器如何修改远程端口?
  • 教程:使用iPhone相机和openCV来完成3D重建(第一部分) ...
  • 说说我为什么看好Spring Cloud Alibaba
  • ​configparser --- 配置文件解析器​
  • #14vue3生成表单并跳转到外部地址的方式
  • (1/2)敏捷实践指南 Agile Practice Guide ([美] Project Management institute 著)
  • (android 地图实战开发)3 在地图上显示当前位置和自定义银行位置
  • (day 2)JavaScript学习笔记(基础之变量、常量和注释)
  • (办公)springboot配置aop处理请求.
  • (第一天)包装对象、作用域、创建对象
  • (九十四)函数和二维数组
  • (力扣题库)跳跃游戏II(c++)
  • (三分钟)速览传统边缘检测算子
  • (转)拼包函数及网络封包的异常处理(含代码)
  • (转)重识new
  • 、写入Shellcode到注册表上线
  • ... fatal error LINK1120:1个无法解析的外部命令 的解决办法
  • .chm格式文件如何阅读
  • .net core 调用c dll_用C++生成一个简单的DLL文件VS2008
  • .NET Core日志内容详解,详解不同日志级别的区别和有关日志记录的实用工具和第三方库详解与示例