双指针解决两数之和、三数之和、四数之和这类求和问题

这种求和找下标数组的算法题本质上都是可以转化为把数组排序以后的双指针问题。

不管求几个数字之和都是转化为最后两个数的和用一个值来比较然后移动指针确定位置。

 

leetcode167. 两数之和 II - 输入有序数组

 

 

 

var twoSum = function(numbers, target) {
    let len = numbers.length;
    let left = 0, right = len - 1;
    while(left < right){
        let sum = numbers[left] + numbers[right];
        if(sum == target){
            return [left+1,right+1];
        } else if (sum < target){
            left++;
        }else {
            right--;
        }
    }
    return [-1,-1];
};

 

leetcode 15. 三数之和

 

 

var threeSum = function(nums) {
    const len = nums.length;
    let res = [];
    nums.sort((a,b) => a - b);
    for(let i = 0; i < len; i++){
        if(nums[i] > 0) break;
        if(i > 0 && nums[i] === nums[i-1]) continue;
        let target = -nums[i];
        let left = i + 1, right = len - 1;
        while(left < right){
            let sum = nums[left] + nums[right];
            if(sum === target){
                res.push([nums[i],nums[left],nums[right]]);
                left++;
                right--;
                while(left < right && nums[left] === nums[left-1]) left++;
                while(left < right && nums[right] === nums[right+1]) right--;
            } else if (sum < target){
                left++;
            } else {
                right--;
            }
        }
    }
    return res;
};

 

leetcode18. 四数之和

 

 

var fourSum = function(nums, target) {
    const len = nums.length;
    let res = [];
    if(len < 4) return res;
    nums.sort((a,b) => a - b);
    for(let i = 0; i < len - 3; i++){
        if(i > 0 && nums[i] === nums[i-1]) continue;
        if(nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target) break;
        let target3 = target - nums[i];
        for(let j = i + 1; j < len - 2; j++){
            if(j > i + 1 && nums[j] === nums[j-1]) continue;
            let target2 = target3 - nums[j];
            let left = j + 1, right = len - 1;
            while(left < right){
                let sum = nums[left] + nums[right];
                if(sum === target2){
                    res.push([nums[i],nums[j],nums[left],nums[right]]);
                    left++;
                    right--;
                    while(left < right && nums[left] === nums[left-1]) left++;
                    while(left < right && nums[right] === nums[right+1]) right--;
                } else if (sum < target2){
                    left++;
                } else {
                    right--;
                }
            }
        }
    }
    return res;
};

 

posted @ 2021-09-20 11:58  jerryfish  阅读(149)  评论(0编辑  收藏  举报