输出array中出现次数最多的数
用类似这种的方法 不用Map
int[] a = new int[10]{1,2,3,4,5,6,7,7,7,7};
public int getPopularElement(int[] a)
{
int count = 1, tempCount;
int popular = a[0];
int temp = 0;
for (int i = 0; i < (a.length - 1); i++)
{
temp = a[i];
tempCount = 0;
for (int j = 1; j < a.length; j++)
{
if (temp == a[j])
tempCount++;
}
if (tempCount > count)
{
popular = temp;
count = tempCount;
}
}
return popular;
}
我想让this.method = 那个出现次数最多的数字 如果所有数都只出现一次的话就this.method = -1
或者出现次数相同的话也是this.method = -1 。
我照着上面的方法写的没法判断每个数只出现一次的情况 还有出现次数相同的情况
求帮忙看看怎么写
public Long getMode() {
Vector vector = cloned();
long [] num = vector.getElements();
// 要写的地方
return this.method;
}
public static int getPopularElement(int[] a)
{
if(a.length < 2){
return a[0];
}
int[] t = new int[a.length];//记录每一个元素出现的次数
int popular = -1;
for (int i = 0; i < a.length; i++)
{
int temp = a[i];
int count = 1;
for (int j = 0; j < a.length; j++)
{
if(j == i){
continue;
}
if (temp == a[j])
count++;
}
t[i] = count;
}
//System.out.println(Arrays.toString(t));
int first = t[0] > t[1] ? t[0] : t[1];
int pos = t[0] > t[1] ? 0 : 1;
int second = t[0] < t[1] ? t[0] : t[1];
for(int i = 2; i < t.length; i++){
if(t[i] >= first){
first = t[i];
pos = i;
continue;
}
if(t[i] >= second){
second = t[i];
}
}
//System.out.println(first + "," + second);
if(first == second ){
return -1;
}else{
return a[pos];
}
}
用一个数组 下标就是当前数据 然后数据来了就累加 最后查看各个数组元素的值
一个数组的长度为n,出现次数的和为n,不同的元素的个数为m,最大出现次数为a。出现次数最小,而没有2个或以上最大出现次数的情况:(m-1)*(a-1)+a=n ;
a = (n-1)/m + 1;
如果a为小数应该下取整。。所以上面代码需要记录不同元素的个数m。
count表示某元素的出现次数,且这个元素出现字数最大。
只要count=a说明最大的出现次数肯定不同。
如何获取不同元素的个数m?
你的代码有如果出现一次相同tempCount++,如果循环完后tempCount等于初始值(没试过代码,但我觉得是从1开始,如果有相同就已经是2了),m++;
我是为了C币来的-_,-