简体   繁体   中英

Find two numbers in an array whose sum equals a target sum

I am trying to solve the following exercise:

Write a function that when passed an array and a target sum return, efficiently with respect to time used, two distinct zero-based indices of any of two numbers, whose sum is equal to the target sum. If there are no two numbers, the function should return null. For example, findTwoSum([ 3, 1, 5, 7, 5, 9 ], 10) should return an array containing any of the following pair indices:

  • 0 and 3 as 3+7 =10

  • 1 and 5 as 1+9=10

 /** * @param {number[]} numbers The array of numbers. * @param {number} sum The required target sum. * @return {number[]} An array of 2 indices. The indices of the two > elements whose sum is equal to sum. */ function findTwoSum(numbers, sum) { // Your code goes here } const indices = findTwoSum([ 3, 1, 5, 7, 5, 9 ], 10); console.log(indices);

I wanted to approach it with a for loop to sum each one of the numbers as:

    let taken= Set()
    for (i=0;i < numbers.length;i++){
      numbers[i]
    }

But I still don't know how to make one number sum with the others.

You can do the inverse and see if there is a number in the array that is equal to the subtraction of the current number with the final sum

 function findTwoSum(numbers, sum) {
  for (let i = 0; i < numbers.length; i++) {
      const num = numbers.indexOf(sum - numbers[i])
      if (num !== -1) return [i, num];
  }
 }
 
 const indices = findTwoSum([ 3, 1, 5, 7, 5, 9 ], 10);
 console.log(indices);

this is solution with O(n^2) time complexity

 function findTwoSum(numbers, sum) { let indices = []; for (let i = 0; i < numbers.length; i++) { for (let j = i + 1; j < numbers.length; j++) { if (numbers[i] + numbers[j] === sum) indices.push([numbers[i], numbers[j]]); } } return indices; } const indices = findTwoSum([3, 1, 5, 7, 5, 9], 10); console.log(indices);

 function getTwoNumberThatAddUpToTargetNumber(array, targetNumber) {
const arrayOfTuples = [];
for (let i = 0; i < array.length; i++) {
  for (let j = i + 1; j < array.length; j++) {
    if (array[i] + array[j] === targetNumber) {
      arrayOfTuples.push([array[i], array[j]]);
    }
  }
}
return arrayOfTuples;

}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM