标签:
https://leetcode.com/problems/top-k-frequent-elements/
class minHeap { // min Heap private: vector<pair<int, int> > array; int alen; void adjust_all() { for (int k=alen-1; k>=0; --k) { adjust(k); } } void swap(int i, int j) { int tmp = array[i].first; array[i].first = array[j].first; array[j].first = tmp; tmp = array[i].second; array[i].second = array[j].second; array[j].second = tmp; } void adjust(int k) { if (k*2+1 >= alen) { return; } int j = k * 2 + 1; if (k*2+2 < alen && array[k*2+1].second > array[k*2+2].second) { j = k * 2 + 2; } if (array[k].second > array[j].second) { swap(k, j); adjust(j); } } public: minHeap(int n) { alen = n; } void add(int num, int freq) { if (array.size() < alen) { array.push_back(make_pair(num, freq)); if (array.size() == alen) { adjust_all(); } } else { if (freq > array[0].second) { array[0].first = num; array[0].second = freq; adjust(0); } } } vector<int> getArray() { vector<int> ret; for (int k=alen-1; k>=0; --k) { ret.push_back(array[k].first); } return ret; } }; class Solution { unordered_map<int, int> umap; public: vector<int> topKFrequent(vector<int>& nums, int k) { int vlen = nums.size(); for (int i=0; i<vlen; ++i) { if (umap.find(nums[i]) != umap.end()) { umap[nums[i]] = umap[nums[i]] + 1; } else { umap[nums[i]] = 1; } } minHeap mh(k); for (unordered_map<int, int>::iterator itr = umap.begin(); itr != umap.end(); ++itr) { mh.add(itr->first, itr->second); } return mh.getArray(); } };
标签:
原文地址:http://www.cnblogs.com/charlesblc/p/5452403.html