2.优先队列的插入数据和进行排序
//leetcode-692
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> cnt;
for (auto& word : words) {
cnt[word]++;
}
auto cmp = [](const pair<string, int>& a, const pair<string, int>& b) {
return a.second == b.second ? a.first < b.first : a.second > b.second;
};
priority_queue<pair<string, int>, vector<pair<string, int>>, decltype(cmp)> que;
for (auto& it : cnt) {
que.emplace(it);
if (que.size() > k) {
que.pop();
}
}
vector<string> ret(k);
for (int i = k - 1; i >= 0; i--) {
ret[i] = que.top().first;
que.pop();
}
return ret;
}
};
3.map按照key或者value进行排序
// leetcode-692
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
map<string, int> record;
vector<string> res;
for (auto word : words) {
record[word]++;
}
vector<pair<string, int>> vectorRecord;
// map不能直接按照key或者value进行排序,必须放置在vector中进行排序
for (auto elem : record) {
vectorRecord.push_back(make_pair(elem.first, elem.second));
}
sort(vectorRecord.begin(), vectorRecord.end(), cmp);
int x = k;
for (auto elem : vectorRecord) {
if (x > 0) {
res.push_back(elem.first);
}
x--;
}
return res;
}
static bool cmp(pair<string, int> a, pair<string, int> b) {
if (a.second == b.second) {
return a.first < b.first;
}
return a.second >= b.second;
}
};