diff options
Diffstat (limited to 'other/top_k_freq_element.cpp')
-rw-r--r-- | other/top_k_freq_element.cpp | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/other/top_k_freq_element.cpp b/other/top_k_freq_element.cpp new file mode 100644 index 0000000..343595f --- /dev/null +++ b/other/top_k_freq_element.cpp @@ -0,0 +1,18 @@ +#include "leetcode.h" + +class Solution { +public: + vector<int> topKFrequent(vector<int> &nums, int k) { + unordered_map<int, int> um; + for (int n : nums) + um[n]++; + vector<int> ans; + priority_queue<pair<int, int>> pqp; + for (auto it = um.begin(); it != um.end(); it++) { + pqp.push(make_pair(it->second, it->first)); + if (pqp.size() > um.size() - k) + ans.push_back(pqp.top().second), pqp.pop(); + } + return ans; + } +}; |