Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output:
Example 2:

Input: nums = [1], k = 1
Output:
Note:

You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

``````class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int num : nums){
map[num]++;
}

vector<int> res;
// pair<first, second>: first is frequency,  second is number
priority_queue<pair<int,int>> pq;
for(auto it = map.begin(); it != map.end(); it++){
pq.push(make_pair(it->second, it->first));
}

for(int i = 0;i < k;i++)
{
res.push_back(pq.top().second);
pq.pop();
}

return res;
}
};``````

``````class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int,int> map;
for(int num : nums){
map[num]++;
}

vector<int> res;
// pair<first, second>: first is frequency,  second is number
priority_queue<pair<int,int>> pq;
for(auto it = map.begin(); it != map.end(); it++){
pq.push(make_pair(it->second, it->first));
if(pq.size() > map.size() - k)
{
res.push_back(pq.top().second);
pq.pop();
}
}

return res;
}
};``````

``````class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
std::unordered_map<int, int> freq;
std::vector<int> ret;
for (auto n : nums)
{
if(1 == ++freq[n])
{
ret.push_back(n);
}
}

std::nth_element(ret.begin(), ret.begin() + k - 1, ret.end(), [&freq] (int l, int r) -> bool {
return freq[l] > freq[r];
});
ret.resize(k);
return ret;
}
};``````