ID:1. 两数之和

68 阅读1分钟

考点:哈希

题目链接

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

思路

一、暴力

遍历数组的每一项,减去这个值得到一个差值,然后在剩下的数组项中寻找这个差值

var twoSum = function(nums, target) {
    for(let i = 0; i < nums.length - 1; i++) {
        const c = target - nums[i];
        for(let j = i + 1; j < nums.length; j++) {
            if(nums[j] === c) return [i ,j];
        }
    }
    return [];
};

二、哈希表

遍历的时候把每一个值存入一个哈希表

参考题解

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