jayati

Top K Frequent Elements

May 22nd, 2023
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.89 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<int> topKFrequent(vector<int>& nums, int k) {
  4.         unordered_map<int, int> freqMap;
  5.         vector<pair<int, int>> freqPairs;
  6.  
  7.         // Count the frequency of each number
  8.         for (int num : nums)
  9.             freqMap[num]++;
  10.  
  11.         // Convert the frequency map into a vector of pairs
  12.         for (const auto& entry : freqMap)
  13.             freqPairs.push_back(entry);
  14.  
  15.         // Sort the vector based on the frequencies in decreasing order
  16.         sort(freqPairs.begin(), freqPairs.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
  17.             return a.second > b.second;
  18.         });
  19.  
  20.         // Create the result array with the top k frequent numbers
  21.         vector<int> result;
  22.         for (int i = 0; i < k && i < freqPairs.size(); i++) {
  23.             result.push_back(freqPairs[i].first);
  24.         }
  25.  
  26.         return result;
  27.     }
Advertisement
Add Comment
Please, Sign In to add comment