Skip to content

Latest commit

 

History

History
34 lines (33 loc) · 981 Bytes

018-4sum.md

File metadata and controls

34 lines (33 loc) · 981 Bytes

双指针解决问题 通过两个for循环,固定i,j两个下标 left,right两个指针寻找解

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function(nums, target) {
    nums = nums.sort((a, b) => a - b)
    let res = new Set();
    for (let i = 0; i < nums.length; i++) {
        for (let j = i + 1; j < nums.length; j++) {
            let left = j + 1;
            let right = nums.length - 1;
            while(left < right) {
                let sum = nums[i] + nums[j] + nums[left] + nums[right];
                if (sum > target) {
                    right--;
                } else if (sum < target) {
                    left++;
                } else {
                    res.add(`${nums[i]},${nums[j]},${nums[left]},${nums[right]}`);
                    left++;
                    right--;
                }
            }
        }
    }
    return Array.from(res).map(i => i.split(','))
};