【问题标题】:I can't understand why break is not working [duplicate]我不明白为什么 break 不起作用[重复]
【发布时间】:2022-01-23 12:40:14
【问题描述】:

所以我正在尝试编写一个函数来检查数组中是否存在重复项。一旦函数检测到重复,我希望它退出循环并返回类型。但是在我的情况下,它会继续循环,就好像中断不存在一样。谁能帮我解释一下为什么会这样?

 public static boolean singleNumber(int[] nums) {
           boolean type = false;
           for (int i = 0; i < nums.length - 1; i++) {
              for (int j = i + 1; j <= nums.length - 1; j++) {
                   if (nums[i] == nums[j]) {
                        type = true;
                        break;
                  }
               }
             }
             return type;
           }

【问题讨论】:

    标签: java for-loop duplicates boolean break


    【解决方案1】:

    即使找到重复值,您当前的逻辑也会继续迭代所有元素。要改变这一点,您需要检查外部 for 循环中的类型值,如果为真,则可以从该循环中中断并返回该值。

    虽然您当前的逻辑将有助于识别重复值,但一旦找到该值将是开销,因为它将继续迭代数组。

    以下是适合您要求的解决方案:

    public class Main {
    public static void main(String[] args) {
        System.out.println( singleNumber(new int[]{1,3,1}) );
    }
    
     public static boolean singleNumber(int[] nums) {
           boolean type = false;
           for (int i = 0; i < nums.length - 1; i++) {
              for (int j = i + 1; j <= nums.length - 1; j++) {
                   if (nums[i] == nums[j]) {
                        type = true;
                        break; // to break out of the inner for loop
                  }
               }
               if( type)   
               {
                   break; // to break out of the outer for loop
               }
             }
             return type;
           }
    

    }

    【讨论】:

      【解决方案2】:

      break 只会退出内部循环,而不是两个循环。一种选择是只返回true 而不是break。如果没有提前返回,则在方法末尾返回false。在这种情况下不需要type 变量。

      【讨论】:

        猜你喜欢
        • 2014-12-12
        • 2014-04-20
        • 1970-01-01
        • 2021-07-10
        • 1970-01-01
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多