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个高频的数字,那么对于这类的统计数字的问题,首先应该考虑用 HashMap 来做,建立数字和其出现次数的映射,然后再按照出现次数进行排序。可以用堆排序来做,使用一个最大堆来按照映射次数从大到小排列,在 C++ 中使用 priority_queue 来实现,默认是最大堆,参见代码如下:

解法一:

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
priority_queue<pair<int, int>> q;
vector<int> res;
for (auto a : nums) ++m[a];
for (auto it : m) q.push({it.second, it.first});
for (int i = ; i < k; ++i) {
res.push_back(q.top().second); q.pop();
}
return res;
}
};

当然,既然可以使用最大堆,还有一种可以自动排序的数据结构 TreeMap,也是可以的,这里就不写了,因为跟上面的写法基本没啥区别,就是换了一个数据结构。这里还可以使用桶排序,在建立好数字和其出现次数的映射后,按照其出现次数将数字放到对应的位置中去,这样从桶的后面向前面遍历,最先得到的就是出现次数最多的数字,找到k个后返回即可,参见代码如下:

解法二:

class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> m;
vector<vector<int>> bucket(nums.size() + );
vector<int> res;
for (auto a : nums) ++m[a];
for (auto it : m) {
bucket[it.second].push_back(it.first);
}
for (int i = nums.size(); i >= ; --i) {
for (int j = ; j < bucket[i].size(); ++j) {
res.push_back(bucket[i][j]);
if (res.size() == k) return res;
}
}
return res;
}
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/347

类似题目:

Kth Largest Element in an Array

Word Frequency

Sort Characters By Frequency

Split Array into Consecutive Subsequences

Top K Frequent Words

K Closest Points to Origin

参考资料:

https://leetcode.com/problems/top-k-frequent-elements/

https://leetcode.com/problems/top-k-frequent-elements/discuss/81602/Java-O(n)-Solution-Bucket-Sort

https://leetcode.com/problems/top-k-frequent-elements/discuss/81635/3-Java-Solution-using-Array-MaxHeap-TreeMap

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 347. Top K Frequent Elements 前K个高频元素的更多相关文章

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

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

  2. [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 ...

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

    给定一个非空的整数数组,返回其中出现频率前 k 高的元素.例如,给定数组 [1,1,1,2,2,3] , 和 k = 2,返回 [1,2].注意:    你可以假设给定的 k 总是合理的,1 ≤ k ...

  4. [LeetCode] Top K Frequent Words 前K个高频词

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

  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. C#版(打败99.28%的提交) - Leetcode 347. Top K Frequent Elements - 题解

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

  7. [leetcode]347. Top K Frequent Elements K个最常见元素

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

  8. [leetcode]347. 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 ...

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

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

随机推荐

  1. python生成多维数组方法总结(多维创建有问题的情况)

    1.一维 list1=[]* #[,,,,] list2=np.arange() #[,,,,] 2.二维(注意) list2=[[]*]* 这种创建是有问题的!! print(list2)list2 ...

  2. Java JDK和IntelliJ IDEA 配置及安装

    序言 初学java,idea走一波先.安装完成,配置配置项. idea 软件 官方下载地址:https://www.jetbrains.com/idea/download/#section=windo ...

  3. 【UOJ#389】【UNR#3】白鸽(欧拉回路,费用流)

    [UOJ#389][UNR#3]白鸽(欧拉回路,费用流) 题面 UOJ 题解 首先第一问就是判断是否存在一条合法的欧拉回路,这个拿度数和连通性判断一下就行了. 第二问判断转的圈数,显然我们只需要考虑顺 ...

  4. shell脚本中判断进程是否存在

    #! /bin/bash PROC_NAME=docker ProcNumber=`ps -ef |grep -w $PROC_NAME|grep -v grep|wc -l` ];then echo ...

  5. Maven配置教程详解

    Maven的安装与配置 一.在https://www.cnblogs.com/zyx110/p/10799387.html中下载以下maven安装包 解压缩即可 根据你的安装路径配置maven环境变量 ...

  6. C# 练习题 打印出100-999之间所有的”水仙花数”

    题目:打印出100-999之间所有的”水仙花数”,所谓”水仙花数”是指一个三位数,其各位数字立方和等于该数本身.例如:153是一个”水仙花数”,因为153=1的三次方+5的三次方+3的三次方.1.程序 ...

  7. Python【day 14】sorted函数、filter函数和map函数的区别

    sorted函数.filter函数和map函数的区别1.作用 前者用于排序, 中者用于筛选, 后者用于返回值(不是特定的筛选或者排序)2.写法 前者 sorted(iterable,key=自定义函数 ...

  8. tomcat的基本应用

    1.JVM基本介绍 JAVA编译型 ---> 编译 C 编译型---> linux --->编译一次 windows --->编译一次 macos ubuntu 跨平台 移值型 ...

  9. ios--NavigationViewController跳转、返回传值

      使用NavigationViewController进行页面跳转时,应该使用pushViewController方法来跳转至下一页面,这样的话,下一页面同样在NavigationViewContr ...

  10. JavaScript中this究竟指向什么?

    摘要: 神奇的this! 原文:JS 中 this 在各个场景下的指向 译者:前端小智 Fundebug经授权转载,版权归原作者所有. 1. this 的奥秘 很多时候, JS 中的 this 对于咱 ...