Leetcode question 1 JavaScript solution to the sum of two numbers

Time:2022-5-10

Sum of two numbers:

Topic setting

Given an integer array nums and a target value target, please find the two integers with sum as the target value in the array and return their array subscripts.
You can assume that each input will correspond to only one answer. However, you cannot reuse the same elements in this array.
Example:

Given num = [2, 7, 11, 15], target = 9
Because num [0] + num [1] = 2 + 7 = 9
So [0, 1] is returned

Algorithm analysis:

1. The problem can be solved easily through two cycles, but the time complexity is O (N2), so it is not recommended to use it

2. The problem is stored by the key value of JS dictionary, and the new array is obtained through the target value. Then judge whether the value exists in the new array, output the result array if it exists, and continue to store the key value pair if it does not exist

Problem solving animation

Leetcode question 1 JavaScript solution to the sum of two numbers

JS problem solving Code:

var twoSum = function(nums, target) {
  var obj = {}
  var brr = []
  for(i=0 ; i<nums.length ; i++){
      var a = nums[i]
      var b = target - a
      if(obj[a] !== undefined){
         brr = [obj[a] , i]
      }else{
          obj[b] = i  
      }
  }
  return brr
};