简体   繁体   中英

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;". 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. The loop terminates as soon as you've inspected the case j == 0 which is incorrect, of course.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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