刷题347. Top K Frequent Elements

一、题目说明

题目347. Top K Frequent Elements,从数组中找出现频度最高的k个数。难度是Medium!

二、我的解答

求出现频度最高的数,首先用hash计算各个数出现的频度,然后找出前k个。

class Solution{
	public:
		vector<int> topKFrequent(vector<int>& nums,int k){
			ump.clear();
			for(int i=0;i<nums.size();i++){
				ump[nums[i]]++;
			}

			vector<int> res;
			int minFre=INT_MAX,minFreIndex=-1;
			for(auto u: ump){
				if(res.size()<k){
					res.push_back(u.first);
					if(minFre > u.second){
						minFre = u.second;
						minFreIndex = res.size()-1;
					}
				}else if(u.second > minFre){
					res[minFreIndex] = u.first;
					
					minFre = INT_MAX;
					for(int j=res.size()-1;j>=0;j--){
						if(minFre > ump[res[j]]){
							minFre = ump[res[j]];
							minFreIndex = j;
						}
					}
				}
			}
			return res;
		}
	private:
		unordered_map<int,int> ump;	
};

性能如下:

Runtime: 40 ms, faster than 5.85% of C++ online submissions for Top K Frequent Elements.
Memory Usage: 11.4 MB, less than 96.77% of C++ online submissions for Top K Frequent Elements.

三、优化措施

用大根堆进行优化:

class Solution{
	public:
		vector<int> topKFrequent(vector<int>& nums,int k){
			unordered_map<int,int> ump;
			priority_queue<pair<int,int>> pq;
			
			for(int i=0;i<nums.size();i++){
				ump[nums[i]]++;
			}
			for(auto u: ump){
				pq.push(make_pair(u.second,u.first));
			}
			vector<int> res;
			for(int i=0;i<k;i++){
				res.push_back(pq.top().second);
				pq.pop();
			} 

			return res;
		}
};

性能如下:

Runtime: 16 ms, faster than 96.21% of C++ online submissions for Top K Frequent Elements.
Memory Usage: 11.5 MB, less than 67.74% of C++ online submissions for Top K Frequent Elements.
posted @ 2020-04-20 08:14  siwei718  阅读(135)  评论(0编辑  收藏  举报