maxNumRepeated([],4) --> 0 maxNumRepeated([1],4) --> 0 maxNumRepeated([1,4,3],4) --> 1maxNumRepeated([1,4,3,4,4,3],4) --> 2 maxNumRepeated([1,4,4,4,3],4) --> 3maxNumRepeated([1,4,3,4,3,4],4) --> 1public 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 忘了去掉了
3 回答
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
你程序的逻辑是前后相等就加1,所以在在上面的1,1计数了1次,在中间4个3就是3次,加上最后的三个3是2次,结果当然就是6了。要改的话,前面的判断没啥必要可以去掉,改成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static int maxNumRepeated(int[] a, int elem)
{
int cont = 0;
int maxNum = 0;
for (int i = 0; i < a.length; i++)
{
if (a[i] == elem)
{
cont++;
if (cont > maxNum) maxNum = cont;
}
else cont = 0;
}
return maxNum;
}
添加回答
举报
0/150
提交
取消