【LeetCode】347. 前 K 個高頻元素

思路

使用最小堆排序完成了TopK問題

代碼

class Solution {
public:
	class cmp {
	public:
		//通過重載操作符來對優先隊列定義排序規則
		bool operator()(pair<int, int>& a, pair<int, int>& b)
		{
			return a.second > b.second;
		}
	};
	vector<int> topKFrequent(vector<int>& nums, int k) {
		//map<int, int> myMap; 
		//不使用map的原因是map底層是紅黑樹,每次插入會進行排序,增加了時間複雜度
		unordered_map<int, int> myMap;
		//統計該值出現的次數
		for (auto num : nums)
		{
			myMap[num]++;
		}
		//遍歷map,用最小堆保存頻率最大的k個元素
		//優先隊列,把最小的元素放在隊首
		priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;
		for (unordered_map<int, int>::iterator beg = myMap.begin(); beg != myMap.end(); beg++)
		{
			pq.push(make_pair(beg->first, beg->second));//壓入該鍵值對
			if (pq.size() > k)//堆中元素多於k個
			{
				pq.pop();
			}
		}
		//取出最小堆中的元素
		vector<int> res;
		while (!pq.empty())
		{
			res.push_back(pq.top().first);
			pq.pop();
		}
		//結果要逆序輸出
		vector<int> tempRes(res.rbegin(), res.rend());
		return tempRes;
	}
};


發佈了99 篇原創文章 · 獲贊 19 · 訪問量 8198
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章