力扣1-两数之和

题目地址:https://leetcode-cn.com/problems/two-sum/

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

思路:用map先存一下,然后去找。

难点:map的用法。

var arr = [0,7,5,8,9]
function twoSum(arr, target){
    let map = new Map()
    for(let i = 0; i< arr.length; i++){
        let result = target - arr[i]
        if (map.has(result)){
            return [map.get(result), i]
        } else {
            map.set(arr[i], i)
        }
    }
}
let result = twoSum(arr, 9)
console.log("result-->>", result) // result-->> [ 0, 4 ]
原文地址:https://www.cnblogs.com/qingshanyici/p/14722372.html