The question goes:
Write a method called mode that returns the most frequently occurring element of an array of integers. Assume that the array has at le
You should use a hashmap for such problems. it will take O(n) time to enter each element into the hashmap and o(1) to retrieve the element. In the given code, I am basically taking a global max and comparing it with the value received on 'get' from the hashmap, each time I am entering an element into it, have a look:
hashmap has two parts, one is the key, the second is the value when you do a get operation on the key, its value is returned.
public static int mode(int []array)
{
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
int max = 1;
int temp = 0;
for(int i = 0; i < array.length; i++) {
if (hm.get(array[i]) != null) {
int count = hm.get(array[i]);
count++;
hm.put(array[i], count);
if(count > max) {
max = count;
temp = array[i];
}
}
else
hm.put(array[i],1);
}
return temp;
}
Here is my answer.
public static int mode(int[] arr) {
int max = 0;
int maxFreq = 0;
Arrays.sort(arr);
max = arr[arr.length-1];
int[] count = new int[max + 1];
for (int i = 0; i < arr.length; i++) {
count[arr[i]]++;
}
for (int i = 0; i < count.length; i++) {
if (count[i] > maxFreq) {
maxFreq = count[i];
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] == maxFreq) {
return i;
}
}
return -1;
}