赞
踩
给定一个非空的整数数组,返回其中出现频率前 k 高的元素。
示例 1:
输入: nums = [1,1,1,2,2,3], k = 2 输出: [1,2]
示例 2:
输入: nums = [1], k = 1 输出: [1]
说明:
解题思路:
1.排序法:使用unordered_map存储数据统计频次,然后排序(时间复杂度看排序算法)
时间复杂度:O(nlogn),n 表示数组长度。首先,遍历一遍数组统计元素的频率,这一系列操作的时间复杂度是 O(n);接着,排序算法时间复杂度为O(nlogn) ;因此整体时间复杂度为 O(nlogn) 。
空间复杂度:O(n),最极端的情况下(每个元素都不同),用于存储元素及其频率的 Map 需要存储 n 个键值对。
2.最小堆:使用priority_queue优先队列(时间复杂度优于nlogn)
解题代码:
1.
2.
- class Solution {
- public:
- vector<int> topKFrequent(vector<int>& nums, int k) {
- assert(k>0);
-
- unordered_map<int,int> freq; //(元素,频次)
- for(int i=0;i<nums.size();i++)
- freq[nums[i]]++;
-
- assert(k<=freq.size());
-
- //扫描freq,维护出现频次最高的K个元素
- //在优先队列中,安装频率排序,所以数据对是(频次,元素)的形式
- priority_queue< pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> > pq; //最小堆
- for(unordered_map<int,int>::iterator it=freq.begin();it!=freq.end();it++)
- {
- if(pq.size()==k)
- {
- if(it->second>pq.top().first) //新遍历到的元素的频次大于优先队列中的队首元素
- {
- pq.pop();
- pq.push(make_pair(it->second,it->first));
- }
- }
- else
- {
- pq.push(make_pair(it->second,it->first));
- }
- }
- vector<int> res;
- while(!pq.empty())
- {
- res.push_back(pq.top().second);
- pq.pop();
- }
- return res;
- }
- };

参考:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。