In JS, use a hash table to realize that the sum of two numbers in the array is equal to the target value

topic:

        Given an integer array nums and an integer target value target, please find the two integers whose sum is the target value target in the array, and return their array subscripts. You can assume that there is only one answer for each input. However, the same element in the array cannot appear repeatedly in the answer. You can return answers in any order.

 

 When we traverse to the number aa, subtract aa from targettarget and get bb. If bb exists in the hash table, we can return the result directly. If bb does not exist, then we need to store aa into the hash table so that it can be used by subsequent traversal numbers.

var twoSum = function (nums, target) {
      let map = new Map()
      for (var i = 0; i < nums.length; i++) {
            // 算出当前数字和目标数字的差
            // 若哈希表中存在该差值
            if (map.has(target - nums[i])) {
                  // 则返回当前索引值和差值索引值,即返回结果
                  return [map.get(target - nums[i]), i]
            } else {
                  // 否则就将当前值作为key,索引作为value存入哈希表
                  map.set(nums[i], i)
            }
      }
      return []
};
console.log(twoSum([3, 2, 4], 6))

Result: Prints out the index corresponding to the sum of the target values

 

Guess you like

Origin blog.csdn.net/qq_41579104/article/details/130007322