【数组】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)

思路:

定义一对指针,指向两头。再定义一对指针,指向中间的两个元素。加起来看看跟target比较一下。决定内部指针怎么移动。
注意结果可能出现重复的结果,需要做一下去重操作。
/**
 * @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;
}

 

posted @ 2016-01-17 22:30  很好玩  阅读(189)  评论(0编辑  收藏  举报