以下为Datawhale Leetcode开源学习思路总结,以下代码均为Leetcode代码,但不一定是最优解,仅供参考学习。
优先队列参考链接c++优先队列(priority_queue)用法详解,若链接失效,自行百度用法。
215. 数组中的第K个最大元素
第一种做法直接排序,然后按地址访问第K
个即可,简单,不做解释;第二种就是使用优先队列,我们采用大顶队,然后弹出k-1
次,最后位于大顶堆top
的位置元素就是我们要的元素,代码如下:
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
vector<int> res;
priority_queue<int, vector<int>, less<int>> q(nums.begin(), nums.end());
while(--k) {
q.pop();
}
return q.top();
}
};
347. 前K个高频元素
本题通过map
的key
、value
结构存储数字及其频次,我们在将unordered_map
元素输入至优先队列中时,不需要先创建一个vector<pair<.., ..>>
,再拷贝至优先队列中,直接将map
结构push
进去即可,我们push
的就是一个pair<.., ..>
,那么题目没啥难度,结合Lambda
表达式和function
函数对象后,代码非常简单,如下:
class Solution {
// class mycmp {
// public:
// bool operator()(const pair<int, int> &a, const pair<int, int> &b) {
// return a.second > b.second;
// }
// };
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
// unordered_map<int, int> mp;
// for(auto x : nums) {
// mp[x]++;
// }
// vector<pair<int, int>> vec(mp.begin(), mp.end());
// sort(vec.begin(), vec.end(),
// [](pair<int, int> &a, pair<int, int> &b)->bool{
// return a.second > b.second;
// }
// );
// vector<int> res;
// for(int i = 0; i < k; ++i) {
// res.push_back(vec[i].first);
// }
// return res;
unordered_map<int, int> mp;
for(auto x : nums) mp[x]++;
// auto func = [](const pair<int, int> &a, const pair<int, int> &b)->bool{return a.second > b.second;};
// priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(func)> q(func);
priority_queue<pair<int, int>, vector<pair<int, int>>, function<bool(pair<int, int> &, pair<int, int>&)>> q(
[](pair<int, int> &a, pair<int, int> &b)->bool {
return a.second > b.second;
}
);
for(auto x : mp) {
q.push(x);
if(q.size() > k)
q.pop();
}
vector<int> res(k, 0);
for(int i = k-1; i >= 0; --i) {
res[i] = q.top().first;
q.pop();
}
return res;
}
};
451. 根据字符出现频率排序
本题也是将map
的pair<.., ..>
结构加入到优先队列,这点与347
题相同,然后我们按照频次排序,最后恢复字符串并返回,不做解释了,直接看代码:
class Solution {
public:
string frequencySort(string s) {
unordered_map<char, int> mp;
for(auto x : s) {
mp[x]++;
}
priority_queue<pair<char, int>, vector<pair<char, int>>, function<bool(pair<char, int> &, pair<char, int> &)>> q(
[](pair<char, int> &a, pair<char, int> &b)->bool {
return a.second < b.second;
}
);
for(auto x : mp) {
q.push(x);
}
string res = "";
while(!q.empty()) {
for(int i = 0; i < q.top().second; ++i)
res += q.top().first;
q.pop();
}
return res;
}
};