below is a code for getting top K frequent elements from an array.the code is correct,but im confused about what the comparator is doing here.why is it "p1.second > p2.second " and not "p1.second < p2.second" ,shouldn't the pair with less count be the one at the top of the heap?Please help!
class Solution {
struct compare {
bool operator() (pair<int, int>p1, pair<int, int>p2) {
return p1.second > p2.second;
}
};
public: vector topKFrequent(vector& nums, int k) {
int n = nums.size();
unordered_map<int, int>m;
for (int i = 0; i < n; i++) {
m[nums[i]]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, compare>pq;
for (auto it = m.begin(); it != m.end(); it++) {
pq.push(make_pair(it->first, it->second));
if (pq.size() > k)
pq.pop();
}
vector<int>v;
while (!pq.empty()) {
pair<int, int>p = pq.top();
v.push_back(p.first);
pq.pop();
}
return v;
**}
};**