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
import java.util.HashMap;
public class SmallestHighestRepeatedNumber { static int arr[] = { 9, 4, 5, 9, 2, 9, 1, 2, 8, 1, 1, 7, 7 };
public static void main(String[] args) {
int mode = mode(arr);
System.out.println(mode);
}
public static int mode(int[] array) {
HashMap hm = new HashMap();
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 || temp > array[i] && count == max) {
temp = array[i];
max = count;
}
} else
hm.put(array[i], 1);
}
return temp;
}
}