I'm trying to create a function with the parameters (number, target) that returns the index of two numbers in a given array that is equal to sum of the target. Here's the code so far:
const twoSum = function (nums, target) {
let num1;
let num2;
let index1;
let index2;
for(let i = 0; i < nums.length; i++){
num1 = nums[i];
num2 = target - num1;
if(nums.includes(num2){
index1 = nums.indexOf(num2);
index2 = nums.indexOf(num1);
}
}
return [index1, index2];
}
The problem is; when the array consists of like numbers, it returns just the index of the first number twice eg twoSum([5,5,3], 10)
returns [0,0]
instead of [0,1]
I don't know exactly what you are looking for, but this will give you what you described.
const twoSum = function (nums, target) {
let num1;
let num2;
let index1;
let index2;
for(let i = 0; i < nums.length; i++) {
num1 = nums[i];
num2 = target - num1;
if(nums.includes(num2)) {
index1 = nums.indexOf(num1);
if(num1 === num2) {
index2 = nums.findIndex((num, i) => num === num2 && i != index1);
if(index2 === -1) return -1; //returns -1 if no second number was found
} else {
index2 = nums.indexOf(num2);
}
return [index1, index2];
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.