Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

How to find K most frequent elements in unsorted vector with C++

1 Answer

0 votes
#include <unordered_map>
#include <algorithm>
#include <iostream> 
#include <vector>
  
bool Compare(std::pair<int, int> p1, std::pair<int, int> p2) {
    if (p1.second == p2.second)
        return p1.first > p2.first;
  
    return p1.second > p2.second;
}
  
void PrintKMostFrequentNumbers(std::vector<int> vec, int K) {
    std::unordered_map<int, int> mp;
    int size = vec.size();
    for (int i = 0; i < size; i++)
        mp[vec[i]]++;
  
    std::vector<std::pair<int, int>> frequent_vec(mp.begin(), mp.end());
 
    std::sort(frequent_vec.begin(), frequent_vec.end(), Compare);
  
    for (int i = 0; i < K; i++)
        std::cout << frequent_vec[i].first << " ";
}
  
int main()
{
    std::vector<int> vec = { 4, 5, 19, 50, 7, 19, 8, 19, 3, 3, 6, 3, 27, 19, 3, 3 };
    int K = 2;
  
    PrintKMostFrequentNumbers(vec, K);
}
 

  
  
  
/*
run:
     
3 19 
     
*/

 



answered Apr 28, 2023 by avibootz
edited Apr 28, 2023 by avibootz

Related questions

1 answer 143 views
1 answer 168 views
1 answer 103 views
1 answer 100 views
1 answer 106 views
1 answer 120 views
...