vendredi 21 mai 2021

Why is 'break;' not working as expected for an if statement inside a nested loop? [duplicate]

I am trying the Two Sum Question on LeetCode. This is my code -

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> output{};
        for(int i = 0; i < nums.size(); i++){
            for(int j = 0; j < nums.size(); j++){
                if (nums[i] + nums[j] == target && i - j != 0){
                    output.push_back(i);
                    output.push_back(j);
                    break;
                }
            }
        }
        return output;
    }
};

For an input of -

[3,2,4]
6

The output is -

[1,2,2,1]

While it should actually be -

[1,2]

which means that the break statement under if in the nested for loop causes the loop to break whenever the if statement is true. But that is not happening here.

Only when I changed the nested for loop's initialization from -

int j = 0;

to

int j = i + 1;

that it works. I understand why it works when j is changed. However, why with j = 0 the code is not working is beyond my understanding. Why is the break statement not working?

Aucun commentaire:

Enregistrer un commentaire