Problem:
Given a non-empty list of words, return the k most frequent elements.
Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.
Example 1:
1 2 3 4 |
Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2 Output: ["i", "love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. |
Example 2:
1 2 3 4 |
Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4 Output: ["the", "is", "sunny", "day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. |
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Input words contain only lowercase letters.
Follow up:
- Try to solve it in O(n log k) time and O(n) extra space.
Idea:
Priority queue / min heap
Solution
C++ / priority_queue O(n log k) / O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// Author: Huahua // Runtime: 13 ms (< 90.31 %) class Solution { private: typedef pair<string, int> Node; typedef function<bool(const Node&, const Node&)> Compare; public: vector<string> topKFrequent(vector<string>& words, int k) { unordered_map<string, int> count; for (const string& word : words) ++count[word]; Compare comparator = [](const Node& a, const Node& b) { // order by alphabet ASC if (a.second == b.second) return a.first < b.first; // order by freq DESC return a.second > b.second; }; // Min heap by frequency priority_queue<Node, vector<Node>, Compare> q(comparator); // O(n*logk) for (const auto& kv : count) { q.push(kv); if (q.size() > k) q.pop(); } vector<string> ans; while (!q.empty()) { ans.push_back(q.top().first); q.pop(); } std::reverse(ans.begin(), ans.end()); return ans; } }; |
Related Problems