c++ - 优先队列函数比较
问题描述
在下面的代码中,当在优先级队列中使用时,比较项是被推送的项吗?因此,在Mycomp
函数中,pair &a
对象是否被添加,并且pair &b
,是否已经在队列中并被比较?
class Solution {
public:
struct Mycomp {
bool operator()(const pair<int, string> &a, const pair<int, string> &b){
if(a.first != b.first) { // comparing the frequency if it is not same then return the one with smallest frequency
return a.first > b.first;
}else{
// if frequency are same then compare the alphabetical order - should return the largest one as the idead is to pop smallest frequency with
// largest alphabetical order
return a.second < b. second;
}
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
//defining a map to keep track of the frequency of the words
std::unordered_map<string, int> hashMap;
for( auto word : words) {
hashMap[word]++;
}
// Now we use the concept of priority queue
std::priority_queue<pair<int, string>,std::vector<pair<int,string>>, Mycomp> pq ;
for(auto ele : hashMap) {
pq.push({ele.second, ele.first});
if(pq.size() > k) {
pq.pop(); // pop the elements with least frequency
}
}
vector<string> result;
while(k--){
result.insert(result.begin(),pq.top().second); // if you use push back, then you need to reverse the vector as pq returns the highest alpabetical order when popping.
pq.pop();
}
return result;
}
};
解决方案
不,第一个参数不是要添加的对象。
你的第二个参数operator()
,通常是刚刚添加的对象。
通常第一个参数是队列的中间元素。
但同样,在某些情况下,这些行为可能会出乎意料,并且取决于所使用的编译器或算法。
推荐阅读
- node.js - Nuxt 的 Docker 构建缺少 core-js 依赖项
- javascript - 是什么导致在这个苗条的应用程序中编译 SASS 失败?
- swagger - 重命名端点 /openapi 和 /openapi/ui
- python - 如何使用 Pandas 为新类别分配值?
- python - 新的 python venv 正在使用全局包
- typescript - 实现“宏”TypeScript 转换器
- facebook - Facebook Graph API:组的 GET 不适用于大多数公共组
- css - 意外的 CSS 溢出故障
- java - 获取 ISO8601 中日期的年数
- amazon-web-services - Lambda 函数中的连接超时错误