Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

18、四数之和 #40

Open
hubvue opened this issue Dec 1, 2019 · 0 comments
Open

18、四数之和 #40

hubvue opened this issue Dec 1, 2019 · 0 comments

Comments

@hubvue
Copy link
Owner

hubvue commented Dec 1, 2019

题目

给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。

注意:

答案中不可以包含重复的四元组。

示例:

给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。

满足要求的四元组集合为:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

题解

解题思路

之前写过三数之和,已经很明白这些n数之和的套路,我的解题方法是,将四数之和多加一次循环,转换成三数之和,然后按照三数之和的逻辑解题。值得欣赏的是处理边界的代码,借鉴的网上大佬的,真的很优雅。

代码

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function(nums, target) {
    let len = nums.length;
    let result = [];
    nums.sort((a,b) => a - b);
    for(let i = 0; i < len - 3; i ++) {
        let first = nums[i];
        if(i > 0 && nums[i] === nums[i - 1]) continue;
        for(let j = i + 1; j < len; j ++) {
            let secound = nums[j];
            let r = len - 1;
            let l = j + 1;
            if(j > i + 1 && nums[j] === nums[j - 1]) continue;
            while(l < r) {
                let left = nums[l];
                let right = nums[r];
                let temp = first + secound + left + right;
                if(temp < target) {
                    l ++;
                } else if(temp > target) {
                    r --;
                } else {
                    result.push([first,secound,left, right])
                    while(l < r && nums[l] === nums[l + 1]) {
                        l ++;
                    }
                    while(l < r && nums[r] === nums[r + 1]) {
                        r --;
                    }
                    l++;
                    r--;
                }
            }
        }
    }
    return result
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant