[LeetCode-01]两数之和

113 阅读1分钟

两数之和

暴力解法,循环两边

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
var twoSum = function (nums, target) {
    let result = []
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j<nums.length;j++ ) {
            if(nums[i] + nums[j] === target) {
                result = [i,j]
                break
            }
        }
    }
    return result
};

使用hash表的方法,减少遍历

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