标签:
题目:
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:
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; }
标签:
原文地址:http://www.cnblogs.com/shytong/p/5137972.html