-2

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    std::vector<int>nums = { 1,2,3,4,5 };
    int target =  7 ;

    for (int i = 0; i < nums.size()-1; i++)
    {
        for (int j = i + 1; j <= nums.size(); i++)
        {
            if (nums[i]+nums[j]==target)
            {
                cout << " [ " << i << " ," << j-1 << " ] ";
            }
        }
    }

    return 0;
}

When I run the program I have two errors:

Debug Assertion Failed , Expression:vector subscript out of range.
Unhandled exception at 0x7938E906 (ucrtbased.dll) in problems.exe: An invalid parameter was passed to a function that considers invalid parameters fatal. ( at line 18 --if(nums[i]+nums[j]==target))

Can someone help me, please?

Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696

2 Answers2

1

There are 2 mistakes in the second for loop in your code:

  1. The condition part should be j < nums.size().
  2. the increment operation should be j++ instead of i++.

Also, while printing the final indices, print j, instead of j-1.

Have a look at the following implementation:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int>nums = { 1,2,3,4,5 };
    int target =  7 ;

    for (std::size_t i = 0; i < nums.size()-1; i++)
    {
        for (std::size_t j = i + 1; j < nums.size(); j++)
        {
            if (nums[i]+nums[j]==target)
            {
                std::cout << " [ " << i << " ," << j << " ] ";
            }
        }
    }

    return 0;
}

Output:

 [ 1 ,4 ]  [ 2 ,3 ] 
Remy Lebeau
  • 505,946
  • 29
  • 409
  • 696
Deepak Tatyaji Ahire
  • 4,241
  • 2
  • 9
  • 27
-1
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}
        for j, num in enumerate(nums):
            i = seen.get(target-num, -1)
            if i != -1:
                return [i, j]
            seen[num] = j
        return [-1, -1]
Blastfurnace
  • 17,981
  • 46
  • 54
  • 68