【问题标题】:Write a function that returns the maximum quantity of non-zero elements between two zero elements编写一个函数,返回两个零元素之间非零元素的最大数量
【发布时间】:2022-12-05 16:51:36
【问题描述】:

给定一个整数数组,我需要找到两个零元素之间非零元素的最大数量

例如:int[] arr = {1,2,0,2,3,4,5,0,1,2,3,4,5,6,7,8,8,0,1}

这应该返回 9。但是,这会返回 4:

static int solution(int[] arr){
        int count = 0;
        int maxCount = 0;

        for(int i = 0; i<arr.length-1;i++){
            if(arr[i]==0 && i< arr.length-2){
                i++;
                while(arr[i]!=0){
                    count++;
                    i++;
                }
                maxCount = count;
            }
        }
        return maxCount;
    }

【问题讨论】:

  • 使用调试器单步执行代码。当你遇到第二个0时,你会看到你有一个i++“太多了”,导致你不再输入while。因为当索引指向数组中的0 时您的while 已退出 - 而您的for 循环会增加下一次循环迭代的索引。
  • 此外,您必须在“for”循环开始时将变量“count”初始化为 0,否则您的代码将继续增加“count”值,它将返回 13 而不是 9

标签: java arrays algorithm


【解决方案1】:

一些问题:

  • 内部循环可能会在数组范围之外运行i
  • 当您找到结尾零,您的代码没有考虑到这个零也是一个新组的开始,并且“错过”了它。
  • count 永远不会重置为零,因此当您进入第二个“组”时它也会不断增加
  • maxCount 是无条件设置的,但只有在新计数大于您已经获得的计数时才应更新它。

还:

  • 奇怪的是,循环顶部的 if 条件使外部循环条件变得更加严格。那么为什么不将 i&lt; arr.length-2 作为循环条件呢?

这是您尝试的更正:

static int solution(int[] arr){
    int count = 0;
    int maxCount = 0;

    for (int i = 0; i < arr.length - 2; i++) { // Stricter loop condition
        if (arr[i] == 0) {
            count = 0; // Reset counter
            // Safety & Look ahead for zero
            while (i + 1 < arr.length && arr[i + 1] != 0) {
                count++;
                i++;
            }
            // Only update if improvement
            if (count > maxCount) maxCount = count;
        }
    }
    return maxCount;
}

但是,您可以通过使用外循环来完成内循环的工作来稍微减少代码:

static int solution(int[] arr){
    int count = 0;
    int maxCount = 0;

    for (int i = 0; i < arr.length; i++) {
        if (arr[i] == 0) {
            if (count > maxCount) maxCount = count;
            count = 0;
        } else {
            count++;
        }
    }
    return maxCount;
}

【讨论】:

  • 不适用于案例 {1,2,0,0,1,2}。返回 2 而不是 0
【解决方案2】:

这段代码对我有用

public static int count(int[] arr){
    int total = 0;
    int count = 0;
    for (int i = 0; i < arr.length-1; i++) {
        count = 0;
        int j = i;
        while(arr[j] != 0){
            count++;
            j++;
        }
        i += count;
        if(count > total){
            total = count;
        }
    }
    return total;
}

【讨论】:

  • 但你给了他一条鱼,而不是教他如何钓鱼 ;)
  • @TomElias Nah,不是真的))这会抛出 IndexOutOfRangeException。解决它。
猜你喜欢
  • 2023-01-31
  • 1970-01-01
  • 2017-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-03-07
  • 2023-01-18
  • 1970-01-01
  • 2017-01-11
相关资源
最近更新 更多