﻿ 【数组】4Sum

### 【数组】4Sum

Given an array S of n integers, are there elements abc, 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:

• Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
• The solution set must not contain duplicate quadruplets.
```    For example, given array S = {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)```

```/**
* @param {number[]} nums
* @param {number} target
* @return {number[][]}
*/
var fourSum = function(nums, target) {
var n=nums.length,temp=0,res=[];

if(nums.length<4){
return [];
}

nums.sort(function(a,b){return a-b;});

for(var i=0;i<n-3;i++){
for(var j=n-1;j>i+2;j--){
temp=target-nums[i]-nums[j];
var a=i+1,
b=j-1;
while(a<b){
var sum=nums[a]+nums[b];
if(sum==temp){
var arr=[nums[i],nums[a],nums[b],nums[j]];
res[res.length]=arr;
a++;
b--;
}else if(sum<temp){
a++;
}else{
b--;
}
}
}
}

return res.unique();
};

Array.prototype.unique = function(){
var res = [];
var json = {};
for(var i = 0; i < this.length; i++){
if(!json[this[i]]){
res.push(this[i]);
json[this[i]] = 1;
}
}
return res;
}```