C++实现LeetCode(347.前K个高频元素),久久派带你了解更多相关信息。
[LeetCode] 347. Top K Frequent Elements 前K个高频元素
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 = 0; 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() + 1); 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 >= 0; --i) { for (int j = 0; 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
类似题目:
Word Frequency
Top K Frequent Words
参考资料:
https://leetcode.com/problems/top-k-frequent-elements/
https://www.zzm8.com/d/file/p/20210809181655165387/20210809181655165388
https://www.zzm8.com/d/file/p/20210809181655165395/20210809181655165396
到此这篇关于C++实现LeetCode(347.前K个高频元素)的文章就介绍到这了,更多相关C++实现前K个高频元素内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/11362.html