Loop through array of numbers
Then for each one of those numbers loop through again and check if number1
+ number2
is equal to your target
and also that number1
and number2
arent at the same position in the array (unless that's okay with you)
and return each index
function twoSum(numbers, target) {
// Loop through the array of numbers
for (let i = 0; i < numbers.length; i++) {
const number1 = numbers[i];
for (let j = 0; j < numbers.length; j++) {
const number2 = numbers[j];
// Check if number1 + number2 is equal to target and also make sure number1 and number2 aren't at the same index in the array
if (number1 + number2 === target && i !== j) {
return `index 1: ${i}, index 2: ${j}`
}
}
}
}
for instance calling this twoSum([1,2,3], 4)
would result in index 1: 0, index 2: 2
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…