简体   繁体   English

计算数组中最大递增数列

[英]Count max increasing number sequence in array

I have to find the max increasing number sequence in this array.我必须在这个数组中找到最大递增的数字序列。 Does anyone know why my code doesn't run?有谁知道为什么我的代码不运行?

public class Array {

public static void main(String[] args) {

    int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

    int counter = 0;
    int maxCounter = 0;

    for (int i : a) {

        if (a[i] < a[i + 1]) {
            counter++;
        }

        if (a[i] > a[i + 1]) {
            maxCounter = counter;
            counter = 0;
        }

    }

    System.out.println(maxCounter);
}

}

You have two bugs, your loop should be an ordinary loop over array indices (not a for-each loop over array contents);您有两个错误,您的循环应该是对数组索引的普通循环(而不是对数组内容的 for-each 循环); and your setting of maxCounter should involve a comparison (not a blind assignment).并且您对maxCounter的设置应该涉及比较(而不是盲目分配)。 Like,喜欢,

for (int i = 0; i + 1 < a.length; i++) { // <-- not a for-each loop
    if (a[i] < a[i + 1]) {
        counter++;
    } else if (a[i] > a[i + 1]) { // <-- An else doesn't hurt
        // maxCounter = counter; // <-- not a blind assignment
        maxCounter = Math.max(maxCounter, counter);
        counter = 0;
    }
}

Working code to find the max number sequence in array.在数组中查找最大数字序列的工作代码。

public class Array {

public static void main(String[] args) {

int[] a = {4,7,15,3,9,22,36,24,28,14,19,27,30,31,2,9,29,30,16,19};

int counter = 1;
int maxCounter = 0;

for (int i = 0; i < a.length - 1 ; i++) {
    if (a[i] < a[i + 1]) {
        counter++;
    } else if (a[i] > a[i + 1]) {
        counter = 1;
    }

    if (counter > maxCounter) {
        maxCounter = counter;
    }
}

System.out.println(maxCounter);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM