Skip to content

Instantly share code, notes, and snippets.

@criskgl
Last active August 25, 2019 15:23
Show Gist options
  • Save criskgl/5a45c8f95f77c6d37c1078878b49e085 to your computer and use it in GitHub Desktop.
Save criskgl/5a45c8f95f77c6d37c1078878b49e085 to your computer and use it in GitHub Desktop.
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