Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
-
class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int,int> mp; for(auto &i : nums) mp[i]++; priority_queue<pair<int,int>> pq; for(auto &i : mp) pq.push(make_pair(i.second, i.first)); vector<int> res; while(k-- > 0 && !pq.empty()) { res.push_back(pq.top().second); pq.pop(); } return res; } };
- Your algorithm‘s time complexity must be better than O(n log n), where n is the array‘s size.