Advertisement
Guest User

P04_MostFrequentNumber

a guest
Sep 19th, 2019
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4.  
  5. int main()
  6. {
  7.     int arr_length;
  8.     std::cin >> arr_length;
  9.  
  10.     if(arr_length <= 0) {
  11.         return 0;
  12.     }
  13.  
  14.     int arr[arr_length] = {0};
  15.     for(int i = 0; i < arr_length; i++) {
  16.         int num;
  17.         std::cin >> num;
  18.         arr[i] = num;
  19.     }
  20.  
  21.     if(arr_length == 1) {
  22.         std::cout << arr[0] << std::endl;
  23.         return 0;
  24.     }
  25.  
  26.     int counter = 1;
  27.     int best_count = 0;
  28.     int best_num = 0;
  29.  
  30.     for(int i = 0; i < arr_length - 1; i++) {
  31.         for(int j = i + 1; j < arr_length; j++) {
  32.             if(arr[i] == arr[j]) {
  33.                 counter++;
  34.             }
  35.         }
  36.  
  37.         if(counter > best_count) {
  38.             best_count = counter;
  39.             best_num = arr[i];
  40.         }
  41.  
  42.         counter = 1;
  43.     }
  44.  
  45.     std::vector<int> most_frequent_nums;
  46.     most_frequent_nums.push_back(best_num);
  47.  
  48.     for(int i = 0; i < arr_length - 1; i++) {
  49.         if(arr[i] == best_num) {
  50.             continue;
  51.         }
  52.  
  53.         for(int j = i + 1; j < arr_length; j++) {
  54.             if(arr[i] == arr[j]) {
  55.                 counter++;
  56.             }
  57.         }
  58.  
  59.         if(counter == best_count) {
  60.             most_frequent_nums.push_back(arr[i]);
  61.         }
  62.  
  63.         counter = 1;
  64.     }
  65.  
  66.     std::sort(most_frequent_nums.begin(), most_frequent_nums.end());
  67.     for(int num : most_frequent_nums) {
  68.         std::cout << num << ' ';
  69.     }
  70.  
  71.     return 0;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement