[https://drive.google.com/file/d/12qIWazKzBr1yJGpo1z106euXVJMKMwEa/view?usp=sharing][1]i have to find the index of two numbers whoose sum = target[number given as argument] i have tried to solve this through for loop but i am not getting the indexex correctly as if the first two numbers of array are 1,1 and target is set as two i am getting answer as [0,0] but i want [0,1]
let arr = [1,1,8,9,7,22,6]
var twoSum = function(nums, target开发者_开发百科) {
for(i=0;i<nums.length;i++){
for(j=i+1;j<nums.length;j++)
if(nums[i] + nums[j]==target){
return [nums.indexOf(nums[i]) , nums.indexOf(nums[j])]
}
}
};
console.log(twoSum(arr, 2))
i am expecting output as [0,1]
but i am getting output as [0,0]
[1]: https://i.stack.imgur.com/n1jo7.png
The indexOf
method returns the first occurrence of a particular value. Since you have 1
in both 0
and 1
indexes, It will only return 0
because it is the first occurrence of 1
.
MDN Documentation
Just return the i
and j
itself.
return [i, j];
Changes made:- Just change the return statement of yours
Code:-
let arr = [1,1,8,9,7,22,6]
var twoSum = function(nums, target) {
for(i=0;i<nums.length;i++){
for(j=i+1;j<nums.length;j++)
if(nums[i] + nums[j]==target){
return [i,j]
}
}
};
console.log(twoSum(arr, 2))
Output:-
node /tmp/fiXkoJ2VkT.js
[ 0, 1 ]
Note let's say you want a sum 9.[0,2]
and [1,2]
both sum up to give 9 but the output will be [0,2]
not [1,2]
as you are checking for 1st element all cases than 2nd element all cases and so on..
Updated section .. {your query}
let arr = [1, 1, 8, 9, 7, 22, 6];
function twoSum(arr, target) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === target) console.log([i, j]);
}
}
}
twoSum(arr, 2);
精彩评论