I am trying to defamiliarize myself with c++ so I have been trying to solve problems on LeetCode. I came across this very simple 2 sum problem. Basically if given some array of numbers and a target value, I need to be able to return the indices of the numbers in that array that sum to the target, it is specified that in the data there is only one solution. So if my target is 9 and I have [2,7,11,15] my output should be [0,1]. However my output for this is [0,1,0]. It has been a while since I coded in C++ so I was hoping someone could explain what might be happening. From my understanding when my code finds the write pairing it should add those values to vector v. Then vector v should have a size of 2 so that if statement (v.empty()) should be false and thus no more values should be able to be added to it. Which is why I am confused that more values are still being added.
class Solution
{
public:
vector<int> twoSum(vector<int> &nums, int target)
{
std::vector<int> v;
for (int i = 0; i < nums.size(); i++)
{
for (int j = 0; j < nums.size(); j++)
{
if (nums[i] + nums[j] == target)
{
if (v.empty())
v.push_back(i);
v.push_back(j);
}
}
}
return v;
}
};