【问题标题】:[java]Longest consecutive integers sequence, debug[java]最长连续整数序列,调试
【发布时间】:2015-12-05 05:51:15
【问题描述】:

我为这个问题写了一个方法: 输入:一个整数数组 返回:最长连续整数序列的长度。 比如:对于 {9,1,2,3},返回 3,因为 {1,2,3}

该方法运行不佳。希望有人可以帮助我调试。

public int solution(int[] arr){
    int counter = 1;
    int max = arr[1];
    //find the max in the array
    for (int i : arr){
        if (i > max){
            max  = i;
        }
    }

    int[] nArr = new int[max];
    for (int i : arr){
        nArr[i] = i;
    }

    List<Integer> counters = new ArrayList<>();
    for (int i = 0; i < max; i++){
        if (nArr[i] == nArr[i+1] - 1){
            counter++;
        }else{
            counters.add(counter);
            counter = 1;
        }
    }

    max = counters.get(1);
    for (int i : counters){
        if (i > max){
            max = i;
        }
    }
 return max;    }

非常感谢!!!

【问题讨论】:

    标签: java arrays integer


    【解决方案1】:

    你不需要使用 ArrayList...如果你想要的只是最大连续整数计数,那么试试这个:

    int[] a = somethingBlaBla;
    int counter = 0; // Stores temporary maxes
    int secCounter = 0; //Stores final max
    
    for(int j = 0; j<a.length-1; j++){ // Iterate through array
        if(a[j] == a[j+1]-1){
            counter++; // If match found then increment counter
           if(counter > secCounter)
               secCounter = counter; // If current match is greater than stored match, replace current match
       }
        else
             counter = 0; // Reset match to accumulate new match
    }
    System.out.println(secCounter);
    

    至于你的方法,我注意到的第一件事是max 的值是数组中的最大 数字,而不是数组的大小。因此,如果我的数组类似于 {1,2,3,45,6,7,8,9},它将抛出 indexOutOfBoundsException,因为它会尝试获取数组中不存在的第 45 个元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-21
      • 2023-03-07
      • 1970-01-01
      • 2021-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多