题目

Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

  1. solution set is:

[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

思路

这道题目和解决3sum的思路是一样的
思路是这样的,首先我们先不考虑去除重复的部分,把代码写出来,就很简单的用for循环,当判断最里面的两个数的时候用while循环.之后写出来了,在考虑怎么才能避免重复,就是跳过已经用过的数字就行了.

代码

var fourSum = function(nums, target) {
    let len = nums.length;
    if (nums.length < 4)
        return [];
    
    nums.sort(function(a, b){return a-b;});
    var res = [];
    
    for (let i = 0; i < len-3; i++) {
        if (i > 0 && nums[i] == nums[i-1]) 
            continue;

        for (let j = i+1; j < len-2; j++) {
            if (j > i + 1 && nums[j] == nums[j-1])
                continue;

            let lo = j+1, hi = len-1;
            let temp;
            while(lo < hi) {
                let sum = nums[i] + nums[j] + nums[lo] + nums[hi];
                if (sum == target) {
                    res.push([nums[i], nums[j], nums[lo], nums[hi]]);
                    temp = nums[lo];
                    while (lo < hi && temp == nums[lo])
                        lo++;
                    temp = nums[hi];
                    while (lo < hi && temp == nums[hi])
                        hi--;
                }
                else if (sum < target) {
                    lo++;
                }
                else {
                    hi--;
                }   
            }   
        }
    }
    return res;
};

Mystery_Wen
12 声望1 粉丝