对于此类问题,应使用哈希图。将每个元素输入到哈希图中需要花费O(n)的时间,而需要花费o(1)来获取该元素。在给定的代码中,我基本上是获取一个全局最大值,并将其与从哈希图中’get’接收到的值进行比较,每次我向其中输入一个元素时,请看一下:
hashmap有两部分,第一部分是键,第二部分是对键执行get操作时返回的值。
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;}


