java - 数组列表中最长的数字序列

标签 java arraylist

我正在尝试执行它,以便打印出相同数字的最长序列。我得到的错误是它告诉我需要一个类或枚举。这是我的代码:

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/

相关文章:

java - 使用流映射 java 8 转换另一个列表

java - 从多个 ArrayList 中删除一个对象

java - 填充ArrayList的最短方法

java - 为什么 ArrayList 在内部使用 Object[](而不是 E[])?

java - Java hashtablelload Factor == 1 是什么意思?

java - 如何通过图中的给定路径覆盖最大数量的节点?

java - 自动选择 JList 顶部新添加的元素

java - 通过单击更改 Android Studio 图像的颜色

java - 我如何遍历所有可能性,将一个 ArrayList 拆分为两个大小为 k 和 (n-k) 的 ArrayList?

java - 删除ArrayList中间的元素后结果是什么?