-
Notifications
You must be signed in to change notification settings - Fork 0
/
frequentWords.txt
34 lines (30 loc) · 1012 Bytes
/
frequentWords.txt
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
692. Top K Frequent Words
Given an array of strings words and an integer k, return the k most frequent strings.
Return the answer sorted by the frequency from highest to lowest.
Sort the words with the same frequency by their lexicographical order.
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k)
{
unordered_map<string, int> mp;
vector<pair<string, int>> vc;
vector<string> res;
for (string s: words)
mp[s]++;
copy(mp.begin(), mp.end(),
back_inserter<vector<pair<string, int>>> (vc));
sort(vc.begin(), vc.end(), [] (const pair<string, int>& a, const pair<string, int>& b)
{
if (a.second == b.second)
return (a.first < b.first);
return a.second > b.second;
});
for (pair p: vc)
{
res.push_back(p.first);
if (--k == 0)
break ;
}
return res;
}
};