Problem Statement:
Give an array of integers return the k most frequent elements.
Example 1:
Input:
[10, 10, 10, 20, 20, 20, 20, 30, 30]
k = 2
Output:
[20, 10]
Example 2:
Input:
[10, 10, 30]
k = 1
Output:
[10]Solution in C++:
class Solution {public:
vector<int> topKFrequent(vector<int>& nums, int k) {unordered_map<int, int> freq;
for(int iter = 0; iter < nums.size(); ++iter){++freq[nums[iter]];
}
priority_queue<pair<int, int>> pq;
for(auto iter = freq.begin(); iter != freq.end(); ++iter){pq.push(pair<int, int>(iter->second, iter->first));
}
vector<int> res;
int i = 0;
while(i++ < k){auto val = pq.top();
res.push_back(val.second);
pq.pop();
}
return res;
}
};
Comments
Post a Comment