Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  71] [ 6]  / answers: 1 / hits: 65298  / 5 Years ago, sun, august 18, 2019, 12:00:00

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


More From » arrays

 Answers
6

I don't understand what is wrong with the solution and I hope that
someone can explain ?




Here you're both inner and outer loop start from 0th so in the case [3,2,4] and target 6 it will return [0,0] as 3 + 3 is equal to target, so to take care of same index element not being used twice created a difference of 1 between outer and inner loop






Make outer loop to start from 0th index and inner loop with value i+1





var twoSum = function(nums, target) {
for(let i = 0; i < nums.length; i++){
for(let j = i+1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
return [i, j]
}
}
}
};

console.log(twoSum([15, 7, 11, 2],9))
console.log(twoSum([3, 2, 4],6))




[#51760] Friday, August 9, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eden

Total Points: 730
Total Questions: 117
Total Answers: 117

Location: Peru
Member since Fri, Oct 14, 2022
2 Years ago
;