0

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;
    }
};
potatoman
  • 11
  • 2
  • Unrelated: If you could split your question up in paragraphs it'd be easier to read and relate to. It'd also be easier to find the actual question in it. – Ted Lyngmo May 06 '22 at 19:41
  • 1
    Note that the formatting that was done as an edit to your question indicates why the second push_back is executed regardless of the if condition. – cigien May 06 '22 at 19:46
  • 1
    General rule of thumb: Indentation is meaningless to a C++ compiler. It can be exceptionally meaningful to humans, though. – user4581301 May 06 '22 at 19:46
  • Thank you so much everyone for the comments! It was the indentation issue. I appreciate all the help! – potatoman May 09 '22 at 13:02

0 Answers0