If two or more elements contend for the maximum frequency, return the element which occurs in the array first.
The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
The following line contains N space separated integers, that denote the value of the elements of the array.
The first and only line of output contains most frequent element in the given array.
Constraints:
0 <= N <= 10^8
Time Limit: 1 sec
Sample Input 1 :
13
2 12 2 11 12 2 1 2 2 11 12 2 6
Sample Output 1 :
2
Sample Input 2 :
3
1 4 5
Sample Output 2 :
1
#include<bits/stdc++.h>
int highestFrequency(int arr[], int n) {
// Write your code here
unordered_map<int ,int>mp;
for(int i=0;i<n;i++)
mp[arr[i]]++;
int maxm=0,ans;
for(int i=0;i<n;i++){
if(mp[arr[i]]>maxm){
maxm=mp[arr[i]];
ans=arr[i];
}
}
return ans;
}
Comments
Post a Comment