这道题中学到的几个知识点:
优先队列的排序规则是什么?
The comparison function used to determine whether one element is smaller than another element.If Compare(x,y) is true, then x is smaller than y.The element returned by Q.top() is the largest element in the priority queue.That is, it has the property that, for every other element x in the priority queue, Compare(Q.top(), x) is false.
pair 的比较规则是什么?
先比较第一个的大小,如果第一个相等,再比较第二个的大小。
具体的函数实现如下:
template<class _Ty1,
class _Ty2> inline
bool operator<(const pair<_Ty1, _Ty2>& _Left,
const pair<_Ty1, _Ty2>& _Right)
{ // test if _Left < _Right for pairs
return (_Left.first < _Right.first ||
!(_Right.first < _Left.first) && _Left.second < _Right.second);
}
依然不明白的问题,为什么 最终得到的结果需要反转?
因为优先队列排序后,顶端是出现频率最小的字母,也是第一个出队列的。所以放入 vector 的时候,也是出现频率最小的字母在 vector 前面。所以需要反转。
为什么不可以直接安排字典序小的在底端?
反转之后字典序大的字母就在前端了,就无法得到正确的答案了。
class Solution {
public:
struct cmp{
bool operator()(const pair<string,int>& a,const pair<string,int>& b){
if(a.second != b.second)
return a.second > b.second;
//小的排在顶端
// else return a.first < b.first;
return a < b;
//如果第二个相等,字典序最大的在顶端
//
// if(a.second == b.second)
// return a < b;
// return a.second > b.second;
}
};
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string,int> myMap;
for(auto& s:words){
myMap[s]++;
}
priority_queue<pair<string,int>,vector<pair<string,int>>,cmp> que;
for(auto &p:myMap){
que.push(p);
if(que.size() > k){
que.pop();
}
}
vector<string> ret;
while(!que.empty()){
ret.push_back(que.top().first);
que.pop();
}
reverse(ret.begin(),ret.end());
//没有看明白为什么需要反转。
return ret;
}
};