6. Top K Frequent Words
Example 1:
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:
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.Solution: (Using Array sorting)
class Solution
{
public:
static bool comparator(const pair<string, int> &a, const pair<string, int> &b)
{
if (a.second == b.second)
{
return a.first < b.first;
}
else
{
return a.second > b.second;
}
}
vector<string> topKFrequent(vector<string> &words, int k)
{
map<string, int> m;
vector<pair<string, int>> v;
vector<string> res;
for (int i = 0; i < words.size(); i++)
{
m[words[i]]++;
}
for (auto itr = m.begin(); itr != m.end(); itr++)
{
v.push_back({itr->first, itr->second});
}
sort(v.begin(), v.end(), comparator);
for (int i = 0; i < k; i++)
{
res.push_back(v[i].first);
}
return res;
}
};Solution: (Using Priority Queue)
Last updated