[英]Why does my code only work when I comment out "break;"?
I am trying to solve a LeetCode question ( 26. Remove Duplicates from Sorted Array ) and my code was not working until I commented out "break;".我正在尝试解决 LeetCode 问题( 26. Remove Duplicates from Sorted Array ),直到我注释掉“break;”,我的代码才起作用。 Could someone explain why this is so?
有人可以解释为什么会这样吗? Here's my code:
这是我的代码:
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;
}
}
Indent your code correctly, and you'll see that the corresponding part reads as:正确缩进你的代码,你会看到相应的部分写成:
int found = 0;
for (int j = 0; j < nums.length; j++) {
if ((nums[i] == nums[j]) && (i != j) && (j < i))
found = 1;
break;
}
You can see, that the break
is not only executed if the condition holds true but in every iteration, so also in the first one.您可以看到,
break
不仅在条件成立时执行,而且在每次迭代中都会执行,第一次也是如此。 The loop terminates as soon as you've inspected the case j == 0
which is incorrect, of course.一旦您检查了不正确的案例
j == 0
,循环就会立即终止。
As you want to terminate the loop only if the condition holds true, just put the two lines after the if-statement into a code block:由于您只想在条件成立时终止循环,只需将 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.