![](/img/trans.png)
[英]Why does this lighting code only work for single lights and break when I add multiple lights?
[英]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.