|
| 1 | +/* |
| 2 | + * @Author: xuezaigds@gmail.com |
| 3 | + * @Last Modified time: 2016-07-09 10:20:41 |
| 4 | + */ |
| 5 | + |
| 6 | +class Solution { |
| 7 | +private: |
| 8 | + struct bigger{ |
| 9 | + bool operator()(pair<int, int> &one, pair<int, int>two){ |
| 10 | + return one.second > two.second; |
| 11 | + } |
| 12 | + }; |
| 13 | +public: |
| 14 | + vector<int> topKFrequent(vector<int>& nums, int k) { |
| 15 | + /* Use unordered_map and priority_queue(minheap) solution. |
| 16 | + * |
| 17 | + * Use unordered_map to avoid red-black hash implement, which takes almost O(n*lgn). |
| 18 | + * We build a min heap with size k, so the time complexity is O(nlgk). |
| 19 | + */ |
| 20 | + unordered_map<int, int> num_count; |
| 21 | + for(const auto &n: nums){ |
| 22 | + num_count[n] += 1; |
| 23 | + } |
| 24 | + |
| 25 | + priority_queue<pair<int, int>, vector<pair<int, int>>, bigger> frequent_heap; |
| 26 | + // Build the min-heap with size k. |
| 27 | + for(auto it = num_count.begin(); it != num_count.end(); it++){ |
| 28 | + if(frequent_heap.size() < k){ |
| 29 | + frequent_heap.push(*it); |
| 30 | + } |
| 31 | + else if(it->second >= frequent_heap.top().second){ |
| 32 | + frequent_heap.pop(); |
| 33 | + frequent_heap.push(*it); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + vector<int> ans; |
| 38 | + while(!frequent_heap.empty()){ |
| 39 | + auto top = frequent_heap.top(); |
| 40 | + frequent_heap.pop(); |
| 41 | + ans.push_back(top.first); |
| 42 | + } |
| 43 | + return ans; |
| 44 | + } |
| 45 | +}; |
| 46 | + |
| 47 | + |
| 48 | +class Solution_2 { |
| 49 | +public: |
| 50 | + vector<int> topKFrequent(vector<int>& nums, int k) { |
| 51 | + /* Using stl heap tool. |
| 52 | + * According to: |
| 53 | + * https://discuss.leetcode.com/topic/46664/36ms-neat-c-solution-using-stl-heap-tool |
| 54 | + */ |
| 55 | + if (nums.empty()) return {}; |
| 56 | + unordered_map<int, int> m; |
| 57 | + for (auto &n : nums) m[n]++; |
| 58 | + |
| 59 | + vector<pair<int, int>> heap; |
| 60 | + for (auto &i : m) heap.push_back({i.second, i.first}); |
| 61 | + |
| 62 | + vector<int> result; |
| 63 | + make_heap(heap.begin(), heap.end()); |
| 64 | + while (k--) { |
| 65 | + result.push_back(heap.front().second); |
| 66 | + pop_heap(heap.begin(), heap.end()); |
| 67 | + heap.pop_back(); |
| 68 | + } |
| 69 | + return result; |
| 70 | + } |
| 71 | +}; |
| 72 | + |
| 73 | +/* |
| 74 | +[1,1,1,2,2,3] |
| 75 | +2 |
| 76 | +[1,1,2,3,3,3,4,4,4,4,1,1,1] |
| 77 | +3 |
| 78 | +*/ |
0 commit comments