Leetcode刷题-1.两数之和(JS)

Leetcode刷题-1.两数之和(JS)

题目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example:

Input: nums = [2,7,11,15], target = 9 Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

输入一个数组和一个target值,返回数组中和为target值的两个数的下标。

思路

  1. 创建一个map
  2. for循环遍历nums数组
  3. 用target减去nums[i],以计算哪个数能跟当前的数字相加得到target
  4. 检查map里有没有这个数,如果有则返回结果;如果没有则把num[i]当做key,i当作value放入map中。(为什么不能把i当作key?)
    答:检查map里有无对应的数时,要调用map.has()函数,它检查的是map里有没有对应的key,如果i在前,就找不到实际的value

代码

var twoSum = function(nums, target) {
  const map = new map();  //创建一个空map
  for(let i=0;i<nums.length;i++){  //遍历数组
      const temp = target - nums[i];  //计算与num[i]相对应的结果
      if (map.has(temp)){  //检查当前map里有没有这个结果
          return [map.get(temp),i]; //如果有,返回其下标
      }else{
          map.set(nums[i],i);  //如果没有,则将当前num[i],i加入map
      }
      return []; //若没有符合要求的数,则返回空值
  }
};

参考资料

https://www.bilibili.com/video/BV1wA411b7qZ?p=1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值