当前位置:首页 > 通信资讯 > 正文

leetcode 前k个高频元素(leetcode 频率)

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

Given a non-empty array of integers, return thekmost 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 assumekis always valid, 1 ≤k≤ number of unique elements.
  • Your algorithm's time complexitymust bebetter than O(nlogn), wherenis the array's size.

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

解法一:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 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个后返回即可,参见代码如下:

解法二:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 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://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

到此这篇关于C++实现LeetCode(347.前K个高频元素)的文章就介绍到这了,更多相关C++实现前K个高频元素内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/grandyang/p/5454125.html

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。