两数之和

122 阅读1分钟

两数之和 ||

示例:

输入: numbers = [2, 7, 11, 15], target = 9
输出: [1,2]

题解一:

var twoSum = function(nums, target) {
    let temps = [];
    for(var i = 0; i< nums.length; i++) {
        let dif = target - nums[i];
        if(temps[dif] != undefined){
            return [temps[dif] + 1, i + 1]
        } else {
            temps[nums[i]] = i
        }
    }
};

题解二:

var twoSum = function (nums, target) {
    let i = 0;
    let j = nums.length - 1;
    
    while(i < j){
        if(numbers[i] + numbers[j] === target) {
            return [i + 1, j + 1]
        } else {
            if(numbers[i] + numbers[j] > target){
                j--;
            } else {
                i++;
            }
        }
    }
}