查找数组中连续数字的数量[java]

时间:2016-10-08 20:19:53

标签: java

例如,数组就像这个{1,1,2,1,1,1},它们的键int是1,最大连续次数1将是3.当我运行我的代码并输入相同的数字,我连续4个数字1.有人能给我建议吗?有没有内置的方法可以帮我解决这个问题?

babel-preset-es2015

5 个答案:

答案 0 :(得分:1)

看起来你应该有第二个内循环,它应该只是

for (int i = 0; i + 1<numb.length; i++){
   if(numb[i] == numb[i + 1]){
      count++;
   }else{
      if(largest<count) {
        largest = count;
        count = 1;
   }
 }

答案 1 :(得分:0)

只需在if条件中将count重新分配给0(在编辑前的初始代码中)。

if(largest<count){
   largest = Math.max(largest, count);
   count = 0;
}

Output

在当前代码中,只需添加一个if条件,检查for循环后max是否大于count。

largest = (largest > count) ? largest : count;

或者

if (count > largest){
   largest = count;
} 

答案 2 :(得分:0)

略有不同的方法。

count = 0;
for (int i : numb){
  if (i == key){
    count++;
  } else {
    count = 0;
  }
  if(largest<count) {
    largest = count;
  }
}

答案 3 :(得分:0)

试试这个。

        int numb[] = new int[] { 6, 3, 3, 5,5,5 ,3, 5, 15,15 };
        int key = 3; // Can be changed
        int largest = 0;
        int currCount = 0;
        for (int i = 0; i < numb.length; i++) {
            if (numb[i] == key) {
                currCount++;
            } else {
                if (currCount > largest) {
                    largest = currCount;
                }
                currCount = 0;
            }
        }
        if (currCount > largest) {
            largest = currCount;
        }

        System.out.println("Largest number of consecutive times " + key + " was entered: " + largest);

答案 4 :(得分:0)

for (int i = 0; i<numb.length; i++) {
    if (numb[i] == key) {
        if(i == numb.length-1){
            count =1;
        }
        else if (numb[i] == numb[i+1]) {
            count++;
        }
        if (count > largest) {
            largest = count;
        }
    }
    else
        count = 1;
}