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,950 questions

51,892 answers

573 users

How to find K most frequent elements in an unsorted array 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(int arr[], int size, int K) {
    std::unordered_map<int, int> mp;
    for (int i = 0; i < size; i++)
        mp[arr[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()
{
    int arr[] = { 4, 5, 19, 50, 7, 19, 8, 19, 3, 3, 6, 3, 27, 19, 3, 3 };
    int size = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
   
    PrintKMostFrequentNumbers(arr, size, K);
}
  
  
  
  
/*
run:
     
3 19 
     
*/

 

 



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

Related questions

1 answer 161 views
1 answer 167 views
1 answer 103 views
1 answer 100 views
1 answer 106 views
1 answer 120 views
...