Java 求问一下怎样求int数组中连续出现最多次数的数~并输出出现了多少次。求高手指点

样例输入
52 1 1 1 2
样例输出

3

public static void main (String args[]){
int[] array = new int[]{5,1,1,1,3,3,3,6,7,7,8,8,8,8,9,1,2,3,4,4};
//连续出现最多的数
int more = 0;
//连续出现最多的次数
int moreCount = 0;
//当前连续出现的次数
int tempCount = 0;
//上一次取出的数
int before = 0;
for(int i=0;i<array.length;i++){
int temp = array[i];
//当前取出的数是不是和上一次取出的数一样
if(temp == before){
//一样当前连续出现次数加1
tempCount++;
}else{
//如果不一样判断上一个数连续出现的次数是不是最多
if(tempCount>moreCount){
moreCount = tempCount;
more = before;
}
before = temp;
tempCount = 1;
}
}
System.out.println(more+"连续出现"+moreCount+"次");

}追问

如果是连续3个1 就算不出

追答

少判断了一步,修改后
public static void main (String args[]){
int[] array = new int[]{5,1,1,1,3,3,3,6,7,7,8,8,8,8,9,1,2,3,4,4,4};
// 连续出现最多的数
int more = 0;
// 连续出现最多的次数
int moreCount = 0;
// 当前连续出现的次数
int tempCount = 0;
// 上一次取出的数
int before = 0;
for(int i=0;imoreCount){
moreCount = tempCount;
more = before;
}
before = temp;
tempCount = 1;
}
}
if(tempCount>moreCount){
moreCount = tempCount;
more = before;
}
System.out.println(more+"连续出现"+moreCount+"次");
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-12-09
大概是最简单粗暴的方法:

int count=0;
int maxcount=0;
int num=array[0];
for(int i=1;i< array.length;i++)
{ if(num==array[i])
{count++;

}

else{
num=array[i];

count=0;

}

if(maxcout<count)

maxcount=count;

}
System.out.print(maxcount);