LeetCode-347. Top K Frequent Elements [C++][Java]
LeetCode-347. Top K Frequent Elementshttps://leetcode.com/problems/top-k-frequent-elements/
题目描述
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
解题思路
【C++】
1. map + vector sort
class Solution {
public:vector<int> topKFrequent(vector<int>& nums, int k) {unordered_map<int,int> um;vector <int> res;for (int i=0;i<nums.size();i++) um[nums[i]]++;vector<pair<int,int>> freq_arr(um.begin(), um.end()); sort(freq_arr.begin(),freq_arr.end(),compare); for (int i = 0; i<k; i++) res.push_back(freq_arr[i].first);return res;}static bool compare(pair<int, int> p1, pair<int, int> p2) { if (p1.second == p2.second) return p1.first > p2.first; return p1.second > p2.second; }
};
2. priority_queue + map
class Solution {
public:vector<int> topKFrequent(vector<int>& nums, int k) {auto cmp = [](const pair<int,int>& p1, const pair<int,int>& p2) {return p1.second > p2.second;};priority_queue<pair<int,int>, vector<pair<int,int>>, decltype(cmp)> q(cmp);unordered_map<int, int> m;for (int i : nums) m[i]++;for (auto& p : m) {if (q.size() < k) q.push(p);else {if (cmp(q.top(), p)) continue;q.push(p);q.pop();}}vector<int> results;for (; !q.empty(); results.push_back(q.top().first), q.pop());return results;}
};
3. 桶排序
class Solution {
public:vector<int> topKFrequent(vector<int>& nums, int k) {unordered_map<int, int> counts;int max_count = 0;for (const int & num : nums) {max_count = max(max_count, ++counts[num]);}vector<vector<int> > buckets(max_count + 1);for (const auto & p : counts) {buckets[p.second].push_back(p.first);}vector<int> res;for (int i = max_count; i >= 0 && res.size() < k; --i) {for (const int & num : buckets[i]) {res.push_back(num);if (res.size() == k) {break;}}}return res;}
};
【Java】
1. HashMap + PriorityQueue
class Solution {public int[] topKFrequent(int[] nums, int k) {Map<Integer,Integer> map= new HashMap<>();for (int a: nums) {map.put(a, map.getOrDefault(a, 0) + 1);}PriorityQueue<Map.Entry<Integer, Integer>> queue =new PriorityQueue<>((a,b) -> b.getValue() - a.getValue());for (Map.Entry<Integer, Integer> entry: map.entrySet()){queue.offer(entry);}int[] result = new int[k];for (int i=0; i<k; i++) {result[i] = queue.remove().getKey();}return result;}
}
2. 桶排序
class Solution {public int[] topKFrequent(int[] nums, int k) {HashMap<Integer, Integer> map = new HashMap<>();int maxCount = 0;for (int i=0; i<nums.length; i++) {map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);maxCount = Math.max(maxCount, map.get(nums[i]));}List<Integer>[] bucket = new List[maxCount + 1];for (int e: map.keySet()) {int freq = map.get(e);if(bucket[freq] == null) {bucket[freq] = new ArrayList<>();}bucket[freq].add(e);}int[] ans = new int[k];int count = 0;for (int i=maxCount; i >= 0 && count < k; i--) {if (bucket[i] == null) {continue;}for (int num : bucket[i]) { ans[count++] = num;if(count == k) break;}}return ans; }
}
参考文献
【1】PriorityQueue的用法和底层实现原理_Hanniboo's Blog-CSDN博客_priorityqueue
【2】你应该知道的 PriorityQueue ——深入浅出分析 PriorityQueue_Java极客技术-CSDN博客
【3】C++中priority_queue理解与使用_不积跬步无以至千里-CSDN博客_c++ priority_queue
LeetCode-347. Top K Frequent Elements [C++][Java]相关推荐
- [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, ...
- Leetcode - 347. Top K Frequent Elements(堆排序)
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- [swift] 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, ...
- leetcode 347. Top K Frequent Elements | 347. 前 K 个高频元素(大根堆)
题目 https://leetcode.com/problems/top-k-frequent-elements/ 题解 参考:leetcode 215. Kth Largest Element in ...
- Leetcode 347. Top K Frequent Elements--python1行解法,Java 11ms解法
题目地址: Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nu ...
- 347. Top K Frequent Elements 前 K 个高频元素
给定一个非空的整数数组,返回其中出现频率前 k 高的元素. 示例 1: 输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2] 示例 2: 输入: nums = [1], ...
- 【LeetCode 剑指offer刷题】查找与排序题12:Top K Frequent Elements
[LeetCode & 剑指offer 刷题笔记]目录(持续更新中...) Top K Frequent Elements Given a non-empty array of integer ...
- Leetcode: Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.For example, Given [1,1,1,2 ...
- leetcode347 - Top K Frequent Elements - medium
Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [ ...
- 力扣347:前k个高频元素---leetcode347:Top K Frequent Elements
leetcode347题目链接:https://leetcode.cn/problems/top-k-frequent-elements 目录 一.题目描述 二.思路 1.什么是优先级队列呢? 2.什 ...
最新文章
- Spark集群搭建中的问题
- 适配器模式理解和使用
- [C++对象模型][8]多重继承与虚函数表
- 微软:明明修复了Bug,你们还把我骂上热搜?
- python-字符串数据类型-定义与输出
- 简单的Spring配置文件
- 高等数学在计算机领域的应用,计算机专业高等数学应用性改革探索论文
- 微信小程序——案例:收货信息表单
- 深度精简版操作系统下IIS的安装方法
- Mybatis 框架CRUD的操作 案例
- 形式化方法 | Proof Engineering for Predicate Logic——Coq tatics 在谓词逻辑证明中的应用
- 金融小知识 | Fama-Macbeth回归
- 微信在服务器上发不了图片大小,为什么微信发不了图片?这四招教你解决难题...
- Google中Gson的巧妙使用 —————— 开开开山怪
- 男主龙失忆java_男主失忆的小说推荐:我忘了全世界,却记得对你的爱,一生不变...
- 串口流控制DCB结构体解析及设置
- 对比测评3款BI分析⼯具,还是它最香!
- mye连接mysql数据库_MySQL_如何在Java程序中访问mysql数据库中的数据并进行简单的操作,在上篇文章给大家介绍了Myeclip - phpStudy...
- 真实的上海IT圈:张江男vs漕河泾男
- 训练数据出现TypeError: 'numpy.float64' object cannot be interpreted as an integer错误
热门文章
- 基于J2EE的弹幕视频网站设计
- 我的练习项目: 模拟淘宝搜索商品、添加商品到购物车功能、修改商品信息功能
- [树形dp] Jzoj P1162 贪吃的九头龙
- 从iOS切换到Android(flyme)
- 打造可用的梅花6硬键盘
- 淘客订单检测接口--检测淘宝订单是否是淘客订单的接口
- WTEM-1Q/GPS瞬变电磁仪操作步骤
- 基于Springboot和Idea的医院管理系统(挂号、缴费、取药、住院) 毕业论文+项目源码及数据库文件+包远程安装配置+代码讲解
- [渝粤教育] 西南科技大学 民法学 在线考试复习资料
- html检测正则表达式,正则表达式在线测试工具