Last active
August 25, 2019 15:23
-
-
Save criskgl/5a45c8f95f77c6d37c1078878b49e085 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int mostFrequent(int arr[], int n) | |
{ | |
// Insert all elements in hash | |
Map<Integer, Integer> hp = | |
new HashMap<Integer, Integer>(); | |
for(int i = 0; i < n; i++) | |
{ | |
int key = arr[i]; | |
if(hp.containsKey(key)) | |
{ | |
int freq = hp.get(key); | |
freq++; | |
hp.put(key, freq); | |
} | |
else | |
{ | |
hp.put(key, 1); | |
} | |
} | |
// find max frequency. | |
int max_count = 0, res = -1; | |
for(Entry<Integer, Integer> val : hp.entrySet()) | |
{ | |
if (max_count < val.getValue()) | |
{ | |
res = val.getKey(); | |
max_count = val.getValue(); | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment