在Java中编写一个模式方法来查找数组中最常出现的元素
问题是:
下面是我的代码几乎可以工作,除了单元素数组 publicstaticintmode(int[]n) { Arrays.sort(n); int count2 = 0; int count1 = 0; int pupular1 =0; int popular2 =0; for (int i = 0; i < n.length; i++) { pupular1 = n[i]; count1 = 0; //see edit for (int j = i + 1; j < n.length; j++) { if (pupular1 == n[j]) count1++; } if (count1 > count2) { popular2 = pupular1; count2 = count1; } else if(count1 == count2) { popular2 = Math.min(popular2,pupular1); } } return popular2; } 编辑:终于弄清楚了.更改count1 = 0;到count1 = 1;一切都奏效了 解决方法
你应该使用hashmap来解决这个问题.将O(n)时间输入到每个元素进入hashmap和o(1)来检索元素.在给定的代码中,我基本上是采取一个全局最大值,并将其与从hashmap’get’接收的值进行比较,每当我进入一个元素时,看看:
hashmap有两个部分,一个是关键,第二个是值,当你在key上做一个get操作时,它的值被返回. public static int mode(int []array) {HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); int max=1,temp; for(int i=0;i<array.length;i++) { if(hm.get(array[i])!=null) {int count=hm.get(array[i]); count=count+1; hm.put(array[i],count); if(count>max) {max=count; temp=array[i];} } else {hm.put(array[i],1);} } return temp; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |