Given an array of integers, return indices of the two numbers such that they add up to a specific target.
Example:
Given nums =
[3, 2, 4]
, target = 6,
Because
nums[1] + nums[2]
= 2 + 4 = 6
return [1, 2]
.
Solution
var twoSum = function(nums, target) {
for(let i = 0; i <= nums.length; i++){
for(let j = 0; j <= nums.length; j++){
if(nums[i] + nums[j] == target){
return [i, j]
}
}
}
};
The code above works in other cases but not this one.
Expected result [1,2]
Output [0,0]
For instance, I've tried to use a different array of numbers and a different target and it works even if you change the order of the numbers
Example:
New array: [15, 7, 11, 2]
, target = 9,
Output: [1, 3]
.
I don't understand what is wrong with the solution and I hope that someone can explain. Thanks