leetcode day01

97 阅读1分钟

第一题

  1. 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

思路: 反向思考: 我们可以用 9 这个target数去减每一个值. 减了第一个数余下的值再去和每一个数去对比, 对比发现找不到后, 就将这个数放进map里面备用. 这里面使用的是map作为数组的存放, 使用了map的几个function, has(), set(); 注意在存放的时候, 我们刻意的将数组里面的value作为map里面的key, 因为使用has去查找的时候, 是查找key里面有没有这个值, 返回value.

var twosum = function(nums, target){
    const map = new map();
    for(let i = 0; i < nums.length; i++){
        const complement = target - num[i];
        if(map.has(complement)) {
            return [map.get(complement), i]
        }else {
            map.set(nums[i], i);
        }
    }
    return [];
}