两数之和

2020-09-18  本文已影响0人  行走的蛋白质
let nums = [2, 7, 11, 15, 3, 8]
let target = 19
function twoSum(arr, tar) {
    for(let i = 0; i < arr.length; i++) {
        for(let j = i + 1; j < arr.length; j++) {
            if(arr[i] + arr[j] === target) {
                return [i, j]
            }
        }
    }
}
function twoSum(arr, tar) {
    const preNums = {}
    for(let i = 0; i < arr.length; i++) {
        let curNum = arr[i]
        let tarNum = tar - curNum
        let tarNumIndex = preNums[tarNum]
        if(tarNumIndex !== undefined) {
            return [tarNumIndex, i]
        } else {
            preNums[curNum] = i
        }
    }
}
function twoSum(arr, tar) {
    let last = arr.pop()
    while(arr.length) {
        if(arr.indexOf(tar - last) > -1) {
            return [arr.indexOf(tar - last), arr.length]
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读