LeetCode-Sum of Two Numbers (js+Map data structure)

topic

Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.

Examples:

Given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9,
so return [0, 1]

Ideas:

  1. Create a map
  2. for loop to traverse nums array
  3. Use target to subtract nums[i] to calculate which number can be added to the current number to get target
  4. Check if there is a number obtained by subtracting nums[i] with target in the map, if there is, return the result, if not, use num[i] as the key and i as the value into the map (why?) u used map .has check the corresponding key in the map

Simulation if: nums=[2,3,11,7] target=
7,6,-2,2
To find 2 and 7 and return 0 and 3
MAP = { 2:0, 3:1, 11:2 } 9 -7 is equal to 2, and there is this number in the map, and the corresponding value of 2 and 7 is found




const twoSum = (nums, target) => {
    
    
  //创建一-个map
    const map = new Map()
    //for循环遍历nums数组
    for (let i= 0; i<nums.length; i++) {
    
    
      //用target减nums[i],以计算哪个数能跟当前的数字相加得到target
      const complement = target - nums[i]
     // 检查map里有没有用target减nums[i]得到的数,如果有则返回结果,如果没有则把num[i]当作key,i当作value放入map中,用到了map.has检查map中对应的key
      if (map.has(complement)) {
    
    
        //如果查找到map中存在就返回两个数对应的下标
        return [map.get(complement),i]
      }else {
    
    
        map.set(nums[i],i)
      }
    }
    return []
}

console.log(twoSum([2,3,11,7],9))//[ 0, 3 ]

Guess you like

Origin blog.csdn.net/pz1021/article/details/105799702