Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions 692. Top K Frequent Words/k_freq_words.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> hashmap;
for(string& word : words) {
hashmap[word] += 1;
}
priority_queue<pair<int, string>, vector<pair<int, string>>, MyComp> pq;
for(auto it = hashmap.begin(); it != hashmap.end(); ++it) {
pq.push(make_pair(it->second, it->first));
if(pq.size() > k) pq.pop();
}
vector<string> res;
while(!pq.empty()) {
// res.insert(res.begin(), pq.top().second);
res.push_back(pq.top().second); // push the results in increasing, and reverse later
pq.pop();
}
reverse(res.begin(), res.end());
return res;
}
private:
struct MyComp {
bool operator() (const pair<int, string>& a, const pair<int, string>& b) {
if(a.first != b.first) {
return a.first > b.first;
}
else {
return a.second < b.second;
}
}
};
};