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. Servlet基本_セッション属性

    1.概念セッション: ユーザーごとの状態を保存する仕組みです.セッションID: アプリケーションサーバから一意の識別子が割り当てられ.これをセッションIDと言う. 2.サーブレットAPIサーブレットA ...

  2. angular的启动原理

    当你用浏览器去访问index.html的时候,浏览器依次做了如下一些事情: 加载html,然后解析成DOM: 加载angular.js脚本:加载完成后自执行,生成全局angular对象,监听DOMCo ...

  3. mysql主从复制搭建中几种log和pos详解

    一.主从原理 Replication 线程   Mysql的 Replication 是一个异步的复制过程,从一个 Mysql instace(我们称之为 Master)复制到另一个 Mysql in ...

  4. [PHP]PHP自定义遍历目录下所有文件的方法

    header('content-type:text/html;charset=utf-8');/** *   方法一:使用readir()遍历目录 */function listDir($dir){  ...

  5. 二:Recovery models(恢复模式)

    For each database that you create in SQL Server, with the exception of the system databases, you can ...

  6. 上任com的发布流程

    参考:https://blog.csdn.net/qq_19674905/article/details/80268815 首先把本地代码提交到远程自己的git分支,然后merge request到m ...

  7. js高级-模块化演变

    function demo(){ var a = b = c = 9; // b,c全局变量 a局部变量 } demo(); console.log(b) 命名空间 var Shop = {} //顶 ...

  8. vue 解决页面闪烁问题

    watch: { //监听表格数据的变化[使用 watch+nextTick 可以完成页面数据监听的 不会出现闪烁] tableData: { //深度监听,可监听到对象.数组的变化 handler( ...

  9. JMeter学习(十七)JMeter测试MongoDB(转载)

    转载自 http://www.cnblogs.com/yangxia-test JMeter测试MongoDB性能有两种方式,一种是利用JMeter直接进行测试MongoDB,还有一种是写Java代码 ...

  10. 单点登录(SSO)解决方案之 CAS服务端数据源设置及页面改造

    接上篇 单点登录(SSO)解决方案之 CAS 入门案例 服务端数据源设置: 开发中,我们登录的user信息都是存在数据库中的,下面说一下如何让用户名密码从我们的数据库表中做验证. 案例中我最终把cas ...