java 返回数组连续重复元素的最大次数

maxNumRepeated([],4) --> 0 
maxNumRepeated([1],4) --> 0 
maxNumRepeated([1,4,3],4) --> 1
maxNumRepeated([1,4,3,4,4,3],4) --> 2 
maxNumRepeated([1,4,4,4,3],4) --> 3
maxNumRepeated([1,4,3,4,3,4],4) --> 1

public static int maxNumRepeated(Integer[] a, Integer elem) {

int cont = 1;
int cont2 = 0;
int maxNum = 0;

if(a.length==1&&a[0].equals(elem)){
maxNum = 1;
}else if(a.length==0){
maxNum = 0;
}else {
for(int i = 0;i<a.length-1;i++){

if(a[i].equals(elem)){

if(a[i].equals(a[i+1])){

cont++;

}
maxNum = cont;
}
}
}
return maxNum;

}
java菜鸟求助啊maxNumRepeated ([1,1,3,3,3,3,2,3,3,3],3)返回的是 6 怎么改才能 返回4呢
忽略 count2 忘了去掉了

一只甜甜圈
浏览 1292回答 3
3回答

慕娘9325324

使用里面的案例,测试过的。~~~~~~~~~~~~~~~~~~~~~~~~~

蝴蝶不菲

你程序的逻辑是前后相等就加1,所以在在上面的1,1计数了1次,在中间4个3就是3次,加上最后的三个3是2次,结果当然就是6了。要改的话,前面的判断没啥必要可以去掉,改成123456789101112131415public static int maxNumRepeated(int[] a, int elem){&nbsp; &nbsp; int cont = 0;&nbsp; &nbsp; int maxNum = 0;&nbsp; &nbsp; for (int i = 0; i < a.length; i++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (a[i] == elem)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cont++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (cont > maxNum) maxNum = cont;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; else cont = 0;&nbsp; &nbsp; }&nbsp; &nbsp; return maxNum;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java