Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<int> topKFrequent(vector<int>& nums, int k) {
- unordered_map<int, int> freqMap;
- vector<pair<int, int>> freqPairs;
- // Count the frequency of each number
- for (int num : nums)
- freqMap[num]++;
- // Convert the frequency map into a vector of pairs
- for (const auto& entry : freqMap)
- freqPairs.push_back(entry);
- // Sort the vector based on the frequencies in decreasing order
- sort(freqPairs.begin(), freqPairs.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
- return a.second > b.second;
- });
- // Create the result array with the top k frequent numbers
- vector<int> result;
- for (int i = 0; i < k && i < freqPairs.size(); i++) {
- result.push_back(freqPairs[i].first);
- }
- return result;
- }
Advertisement
Add Comment
Please, Sign In to add comment