Skip to content

Instantly share code, notes, and snippets.

@lukeknxt
Last active March 21, 2022 05:10
Show Gist options
  • Save lukeknxt/e65c1a1cfe09a9f757989d0aa88e8415 to your computer and use it in GitHub Desktop.
Save lukeknxt/e65c1a1cfe09a9f757989d0aa88e8415 to your computer and use it in GitHub Desktop.
Why though
// scala version
def mostFrequent(arr: Array[Int]): Int = {
arr.groupBy(identity).maxBy(_._2.size)._1
}
// java version (from https://www.geeksforgeeks.org/frequent-element-array/)
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
class GFG {
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