Ton*_*yGW 9 java arrays methods mode
问题是:
编写一个名为mode的方法,它返回整数数组中最常出现的元素.假设数组至少有一个元素,并且数组中的每个元素都具有0到100之间的值(包括0和100).通过选择较低的值来打破关系.
例如,如果传递的数组包含值{27,15,15,11,27},则您的方法应返回15.(提示:您可能希望查看本章前面的Tally程序以了解如何解决这个问题呢.)
下面是我的代码几乎可以工作,除了单元素数组
public static int mode(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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:终于搞清楚了.改count1 = 0;到count1 = 1;一切正常吧!
cod*_*a23 13
你应该使用hashmap来解决这些问题.将每个元素输入到散列映射中需要O(n)时间,并且o(1)需要检索元素.在给定的代码中,我基本上采用全局最大值并将其与从hashmap中的'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;
}
Run Code Online (Sandbox Code Playgroud)