Given a non-empty array of integers, return the k most frequent elements.

Example 1:

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

Example 2:

Input: nums = [1], k = 1
Output: [1]

Note:

  • You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  • Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

题目

给定数组,求其中出现频率最高的K个元素。

思路

bucket sort

代码

 /*
 Time: O(n)
 Space: O(n)
 */
 class Solution {
      public List<Integer> topKFrequent(int[] nums, int k) {
         // freq map
         Map<Integer, Integer> map = new HashMap<>();
         for (int num : nums) {
             map.put(num, map.getOrDefault(num, 0) + 1);
         }
         // bucket sort on freq
         List<Integer>[] buckets = new List[nums.length + 1];
         for (int i : map.keySet()) {
             int freq = map.get(i);
             if (buckets[freq] == null) {
                 buckets[freq] = new ArrayList<>();
             }
             buckets[freq].add(i);
         }
         // gather result
         List<Integer> res = new ArrayList<>();
         for (int i = buckets.length - 1; i >= 0; --i) {
             if (buckets[i] == null) continue;
             for (int item : buckets[i]) {
                 res.add(item);

                 if (k == res.size()) return res;
             }
         }
         return res;
     }
 }

思路

priorityqueue to track Top K Frequent Elements

1. Using HashMap and PriorityQueue
2. Build a HashMap to get the item frequency
3. PriorityQueue (minHeap) 
4.  If the PQ size > k, then we pop the lowest value in the PQ

[leetcode]692. Top K Frequent Words K个最常见单词完全思路一致

代码

 /*
 Time: O(nlogk)
 Space: O(k)
 */
 class Solution {
     public List<Integer> topKFrequent(int[] nums, int k) {
         // freq map
         Map<Integer, Integer> map = new HashMap();
         for(int num : nums){
             map.put(num, map.containsKey(num) ? map.get(num) + 1 : 1);
         }
         // maintain a k-size minHeap
         PriorityQueue <Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>((entry1, entry2) -> entry2.getValue() - entry1.getValue());

         for(Map.Entry<Integer, Integer> entry : map.entrySet()){
             minHeap.add(entry);
         }

         List<Integer> result = new ArrayList<>();
         while(!minHeap.isEmpty() && result.size() < k){
             result.add(0, minHeap.remove().getKey());
         }
         return result;
     }
 }

[leetcode]347. Top K Frequent Elements K个最常见元素的更多相关文章

  1. [leetcode]692. Top K Frequent Words K个最常见单词

    Given a non-empty list of words, return the k most frequent elements. Your answer should be sorted b ...

  2. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  3. [LeetCode] 347. Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  4. [LeetCode] Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  5. 347. Top K Frequent Elements (sort map)

    Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...

  6. Top K Frequent Elements 前K个高频元素

    Top K Frequent Elements 347. Top K Frequent Elements [LeetCode] Top K Frequent Elements 前K个高频元素

  7. 【LeetCode】347. Top K Frequent Elements 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 解题方法 字典 优先级队列 日期 题目地址:https://l ...

  8. LeetCode 【347. Top K Frequent Elements】

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  9. Leetcode 347. Top K Frequent Elements

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

随机推荐

  1. 17_react脚手架应用分析

    |-- index.html // 启动页(主页) |-- build //构建目录,遵循发布系统规范 | |-- index.html //静态页面 | |-- static //资源文件发布到cd ...

  2. Elasticsearch之优化

    为什么es需要优化? 答: [root@master elasticsearch-2.4.0]# ulimit -a core file size (blocks, -c) 0 data seg si ...

  3. b2BuoyancyController 使用浮力

    package{ import Box2D.Collision.b2AABB; import Box2D.Collision.b2RayCastInput; import Box2D.Collisio ...

  4. Python文件和目录模块介绍:glob、shutil、ConfigParser

    glob模块 查找符合特定规则的文件路径名,路径名可以使用绝对路径也可以使用相对路径.查找文件会使用到三个通配符,星号*,问号?和中括号[],其中"*"表示匹配0~n个字符, &q ...

  5. VC++ 自定义控件的建立及使用方法

    一.VC++定义自定义控件与delphi,VB有些差异. delphi,vb在 file-new-other中建立.vc++在工具栏中就有自定义控件,但必须加入控件类型. 许多书籍都在类向导中建立.我 ...

  6. hive\hadoop 常用命令

    —1—————— 后台跑程序语句: 在shell下输入: nohup hive -f  aaa.sql >bbb.log 2>&1 & 然后把sql 的脚本导入服务器上:T ...

  7. sql语句查询菜单结果成 树状图类型 注意适用于id是四位数

    select * from ( select pid,id,name,url,concat(id,":") idOrder from menu where pid=0 and st ...

  8. cdnbest节点安装后连不上cdn主控原因排查

    1. 查看节点程序是否启动 ps -aux |grep kangle 2. 登陆cdn节点用telnet命令查下和主控的通信,命令:telnet 主控ip 3320 3. 如果节点程序都有启动,可查看 ...

  9. msf客户端渗透(三):提权、图形化payload

    对普通权限session提权 生成一个木马 开启Apache服务 将木马上传网页 被攻击者从这个网页上获取到这个木马 攻击者开启msf侦听 当被攻击者双击这个木马文件时 攻击者就获取到一个sessio ...

  10. 如何用 Postman 处理 json请求格式

    下边是其他博友写的 http://blog.163.com/huan12_8/blog/static/130519090201611711213719/