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. Leetcode 题解 Combinations:回溯+求排列组合

    罗列出从n中取k个数的组合数组. 首先,求C(n,k)这个实现,很粗糙,溢出也不考虑,好的方法也不考虑.笨蛋.心乱,上来就写.. 另外,发现在递归中,不能申请太大的数组?貌似不是这个问题,是我自己越界 ...

  2. python multithread task_done

    queue.task_done()用在queue消费者中,在queue.get()调用之后调用queue.task_done()用于通知队列已经完成了工作,使queue.join()知道任务已经完成. ...

  3. python tuple排序

    tuple排序,按照索引0,1,2,3...依次比较 a = [3,1,0,9,6,2,4,8,7,5] a.sort(key = lambda x: (x%2, x, x%3)) # 先按照x%2的 ...

  4. c++复习:STL之容器

    1 STL的string 1 String概念 string是STL的字符串类型,通常用来表示字符串.而在使用string之前,字符串通常是用char*表示的.string与char*都可以用来表示字 ...

  5. 安装安卓SDK和JDK的简便方法

    直接在VS的安装程序里选:使用.NET的移动开发,其中就包括了安卓SDK,JAVA SE等 另外:自己手动安装SDK时,不要选模拟器相关的东西,太大了,如果每个版本都选,安装下来上100G以上

  6. select min from 连接

    预先准备 create table p( name ) ); insert into p values('黄伟福'); insert into p values('赵洪'); insert into ...

  7. csredis base usage

    Basic usage Whenever possible, server responses are mapped to the appropriate CLR type. using (var r ...

  8. C++ new 和malloc 区别

    1.分配地方不同,malloc是堆上面,new是自由存储区域 2.malloc/delete是函数,new/delete是操作符,可以重载 3.malloc 要指定大小,返回的是void*指针,开辟的 ...

  9. SQL--结构化的查询语言

    SQL--结构化的查询语言T-SQL:Transact-SQL (SQL的增强版) 逻辑运算符 and && or || not ! 关系运算符 等于 = 不等于<>或!= ...

  10. ubuntu 下安装和启动SSH 服务

    安装OPENSSH 服务端 sudo apt-get install openssh-server 查看进程是否启动 ps -e | grep ssh 删除密钥文件 rm /etc/ssh/ssh_h ...