Skip to content

Commit 1ddb206

Browse files
Created k_freq_words.cpp
Given an array of strings words and an integer k, return the k most frequent strings.
1 parent c407b0d commit 1ddb206

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
class Solution {
3+
public:
4+
vector<string> topKFrequent(vector<string>& words, int k) {
5+
unordered_map<string, int> hashmap;
6+
for(string& word : words) {
7+
hashmap[word] += 1;
8+
}
9+
priority_queue<pair<int, string>, vector<pair<int, string>>, MyComp> pq;
10+
for(auto it = hashmap.begin(); it != hashmap.end(); ++it) {
11+
pq.push(make_pair(it->second, it->first));
12+
if(pq.size() > k) pq.pop();
13+
}
14+
vector<string> res;
15+
while(!pq.empty()) {
16+
// res.insert(res.begin(), pq.top().second);
17+
res.push_back(pq.top().second); // push the results in increasing, and reverse later
18+
pq.pop();
19+
}
20+
reverse(res.begin(), res.end());
21+
return res;
22+
}
23+
private:
24+
struct MyComp {
25+
bool operator() (const pair<int, string>& a, const pair<int, string>& b) {
26+
if(a.first != b.first) {
27+
return a.first > b.first;
28+
}
29+
else {
30+
return a.second < b.second;
31+
}
32+
}
33+
};
34+
};
35+

0 commit comments

Comments
 (0)