[leetcode]347. Top K Frequent Elements
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode]347. Top K Frequent Elements相关的知识,希望对你有一定的参考价值。
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm‘s time complexity must be better than O(n log n), where n is the array‘s size.
Subscribe to see which companies asked this question
Solution:
1.使用hashtable获取每个元素出现的次数
2.使用小根堆heap排序(priority queue实现),获取前K个出现次数最多的元素pair
3.输出,注意是小根堆,要reverse一下
1 class CompareDist 2 { 3 public: 4 bool operator()(pair<int, int> n1, pair<int, int> n2) 5 { 6 return n1.second > n2.second; 7 } 8 }; 9 10 class Solution { 11 public: 12 vector<int> topKFrequent(vector<int>& nums, int k) 13 { 14 vector<int> ret; 15 unordered_map<int, int> htable; 16 17 for (int key : nums) // get each key appears times 18 htable[key]++; 19 20 priority_queue<pair<int, int>, vector<pair<int, int> >, CompareDist> sheap; // use min heap to get k biggest 21 for (auto elem : htable) 22 { 23 if (sheap.size() < k) 24 { 25 sheap.push(elem); 26 } 27 else 28 { 29 pair<int, int> heap_min = sheap.top(); 30 if (elem.second > heap_min.second) 31 { 32 sheap.pop(); 33 sheap.push(elem); 34 } 35 } 36 } 37 38 while (!sheap.empty()) 39 { 40 pair<int, int> heap_min = sheap.top(); 41 ret.push_back(heap_min.first); 42 sheap.pop(); 43 } 44 reverse(ret.begin(), ret.end()); 45 46 return ret; 47 } 48 };
以上是关于[leetcode]347. Top K Frequent Elements的主要内容,如果未能解决你的问题,请参考以下文章
#Leetcode# 347. Top K Frequent Elements
Leetcode 347: Top K Frequent Elements
LeetCode OJ 347. Top K Frequent Elements hashmap+排序求解
leetcode347 - Top K Frequent Elements - medium