public static int[] longestSeq(int[] a) {
int longestSeq = 1;
int longestInd = 0;
for (int i = 0; i < a.length-1; i++) {
int counter = 1;
while (a[i] == a[i + 1]){
counter++;
i++;
}
if (counter > longestSeq){
longestSeq = counter;
longestInd = i;
}
}
return new int[] {longestSeq, longestInd};
}
错误是什么?代码试图找出整数数组中最长的连续序列。有什么办法可以做到呢?
它可能在您的while
循环中越界,在那里您直接访问i+1
而没有绑定检查
while(i < a.length - 1 && a[i] == a[i + 1]){
counter++;
i++;
}