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?
P. S. Here is the Python code where break
works with a similar logic and for the same input -
class Solution(object):
def twoSum(self, nums, target):
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target and i - j != 0:
return [i, j]
break
else:
continue