Find top three repeated in array | C ++ Program to Find the top three repeated numbers ; Function to print top three repeated numbers ; There should be atleast two elements ; Count Frequency of each element ; Initialize first value of each variable of Pair type is INT_MIN ; If frequency of current element is not zero and greater than frequency of first largest element ; Update second and third largest ; Modify values of x Number ; If frequency of current element is not zero and frequency of current element is less than frequency of first largest element , but greater than y element ; Modify values of third largest ; Modify values of second largest ; If frequency of current element is not zero and frequency of current element is less than frequency of first element and second largest , but greater than third largest . ; Modify values of z Number ; Driver 's Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void top3Repeated ( int arr [ ] , int n ) { if ( n < 3 ) { cout << " Invalid ▁ Input " ; return ; } unordered_map < int , int > fre ; for ( int i = 0 ; i < n ; i ++ ) fre [ arr [ i ] ] ++ ; pair < int , int > x , y , z ; x . first = y . first = z . first = INT_MIN ; for ( auto curr : fre ) { if ( curr . second > x . first ) { z = y ; y = x ; x . first = curr . second ; x . second = curr . first ; } else if ( curr . second > y . first ) { z = y ; y . first = curr . second ; y . second = curr . first ; } else if ( curr . second > z . first ) { z . first = curr . second ; z . second = curr . first ; } } cout << " Three ▁ largest ▁ elements ▁ are ▁ " << x . second << " ▁ " << y . second << " ▁ " << z . second ; } int main ( ) { int arr [ ] = { 3 , 4 , 2 , 3 , 16 , 3 , 15 , 16 , 15 , 15 , 16 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; top3Repeated ( arr , n ) ; return 0 ; }