class Solution {
public:
class compare{
public:
bool operator()(pair<int, string> a, pair<int, string> b){
if (a.first < b.first) return true;
else if (b.first < a.first) return false;
else return a.second < b.second;
}
};
vector<string> topKFrequent(vector<string> combo, int k) {
// write your solution here
if (combo.empty()){
vector<string> res;
return res;
}
// first construct a map
unordered_map<string, int> m;
// populate the map
for (auto & c : combo)
m[c]++;
priority_queue< pair<int, string>, vector< pair<int, string> >, compare> pq;
for (unordered_map<string, int>::iterator it = m.begin(); it != m.end(); it++){
pq.push(make_pair(it->second, it->first));
}
vector<string> res;
for (int i = 0; i < k; i++){
res.push_back(pq.top().second);
pq.pop();
}
return res;
}
};
Easy mistake when defining the comparator...
1 Response
Write a comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.