繁体   English   中英

为什么我的代码只有在我注释掉“break;”时才有效?

[英]Why does my code only work when I comment out "break;"?

我正在尝试解决 LeetCode 问题( 26. Remove Duplicates from Sorted Array ),直到我注释掉“break;”,我的代码才起作用。 有人可以解释为什么会这样吗? 这是我的代码:

class Solution {
    public int removeDuplicates(int[] nums) {
        int read = 0;
        int write = 0;
        
        for (int i = 0; i < nums.length; i++) {
            int found = 0;
            for (int j = 0; j < nums.length; j++) {
                if ((nums[i] == nums[j]) && (i != j) && (j < i))
                    found = 1;
                   // break;
                }
            
            if (found == 0) {
                nums[write] = nums[read];
                write++;
            }
            
            read++;
            
        }
        return write;
    }
}

正确缩进你的代码,你会看到相应的部分写成:

            int found = 0;
            for (int j = 0; j < nums.length; j++) {
                if ((nums[i] == nums[j]) && (i != j) && (j < i))
                    found = 1;
                break;
            }

您可以看到, break不仅在条件成立时执行,而且在每次迭代中都会执行,第一次也是如此。 一旦您检查了不正确的案例j == 0 ,循环就会立即终止。

由于您只想在条件成立时终止循环,只需将 if 语句后的两行放入代码块中:

            int found = 0;
            for (int j = 0; j < nums.length; j++) {
                if ((nums[i] == nums[j]) && (i != j) && (j < i)) {
                    found = 1;
                    break;
                } 
            }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM