【Javascript】leetcode 18.4Sum

Given an array nums of n integers and an integer target, are there elements abc, and d in nums 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.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

思路:同理15题的3Sum

遍历fst和nxt,移动lo和hi去找符合的四元祖

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[][]}
 */
var fourSum = function(nums, target) {
    nums.sort((a,b) => a-b);
    let len = nums.length;
    let rst = [];
    if(len < 4 || (len ==4 && nums.reduce((a,b)=>a+b)!=target)){
       return rst;
       }
    if(len==4 && nums.reduce((a,b)=>a+b)==target){
        rst.push(nums);
        return rst;
    }
    let fst = 0,nxt = 1,lo = 2,hi = len-1;
    while(fst <= len-4){
          while(nxt <= len-3){
            while(lo < hi){
                if(nums[lo] + nums[hi] == (target - nums[fst] - nums[nxt])){
                    rst.push([nums[fst],nums[nxt],nums[lo],nums[hi]]);
                    while(nums[lo+1] == nums[lo]){lo++;}
                    while(nums[hi-1] == nums[hi]){hi--;}
                    lo++;
                    hi--;
                }
                else if (nums[lo] + nums[hi] < (target - nums[fst] - nums[nxt])){
                    lo++;
                }else{hi--;}

            }
          while(nums[nxt+1]==nums[nxt] && nxt <= len-3){nxt++}
          nxt++;
          lo = nxt + 1;
          hi = len - 1;
        }
        while(nums[fst+1] == nums[fst] && fst <= len-4){fst++;}
        fst++;
        nxt = fst + 1;
        lo = nxt + 1;
        hi = len - 1;

    }
    return rst;
};

 

你可能感兴趣的:(leetcode)