我正在尝试执行它,以便打印出相同数字的最长序列。我得到的错误是它告诉我需要一个类或枚举。这是我的代码:
public class D4 {
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 6, 6, 45, 2, 2, 2};
System.out.println(getLongestRun(array));
}
}
最佳答案
这属于评论,但我会给你完整的代码,这样就清楚了。只需在 getLongestRun()
方法的末尾返回 max
:
private static int getLongestRun(int[] array) {
int count = 1;
int max = 1;
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
count++;
}
else {
count = 1;
}
if (count > max) {
max = count;
}
}
// you forgot to return the length of the longest sequence to the caller
return max;
}
关于java - 数组列表中最长的数字序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41787992/