我必须在此数组中找到最大递增数序列。
有谁知道为什么我的代码无法运行?
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);
}
}
最佳答案
您有两个错误,您的循环应该是数组索引的普通循环(而不是数组内容的for-each循环);并且maxCounter
的设置应包含一个比较(而不是盲目分配)。喜欢,
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;
}
}