两数之和

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

  借助api

function twoSum(nums,target){
    for(let i = 0;i < nums.length;i++){
        let item = nums[i]
        if(nums.indexOf(target - item) > -1 && nums.indexOf(target - item) != i){
            return [i,nums.indexOf(target - item)].sort()
        }
    }
}

  双层循环不可用 时间复杂度O(n^2)

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

  双指针(需已排序数组)

// 双指针思路
const twoNumsSumByDoublePointer = (arr = [1,2,3,4,5,6,7,8,9], sum = 6) => {
    let startIndex = 0
    let endIndex = arr.length - 1
    while(startIndex < endIndex){
        const startValue = arr[startIndex]
        const endValue = arr[endIndex]
        const sumValue = startValue + endValue
        if(sumValue > sum){
            endIndex--
        }else if(sumValue < sum){
            startIndex++
        }else{
            return [startIndex, endIndex]
        }
    }
    return []
}

Leecode提交通过

posted @ 2020-06-10 21:42  671_MrSix  阅读(95)  评论(0编辑  收藏  举报