https://leetcode.com/problems/top-k-frequent-elements/description/
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> mp;
vector<int> res;
vector<pair<int,int>> v;
for(int n: nums) mp[n]++;
for(auto &m: mp) v.push_back({m.first,m.second});
sort(v.begin(),v.end(), [&](pair<int,int>&a, pair<int,int>&b){return a.second>b.second;});
for(int i=0; i<k; i++) res.push_back(v[i].first);
return res;
}
Solution 2. Use priority_queue
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> mp;
for(int n: nums) mp[n]++;
priority_queue<pair<int,int>> q;
for(auto &m : mp) q.push({m.second, m.first});
vector<int> res;
for(int i=0; i<k; i++) {
res.push_back(q.top().second);
q.pop();
}
return res;
}
or,
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> mp;
for(int n: nums) mp[n]++;
map<int,vector<int>> buck;
for(auto &m : mp) {
buck[m.second].push_back(m.first);
}
vector<int> res;
for(map<int,vector<int>>::reverse_iterator it=buck.rbegin(); it!=buck.rend(); it++) {
for(auto& n: it->second) {
res.push_back(n);
if(res.size()==k) return res;
}
}
return res;
}
No comments:
Post a Comment