您的位置:首页 > 其它

leetCode 18.4Sum (4数字和) 解题思路和方法

2015-07-06 16:00 351 查看
4Sum

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:

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)

思路:此题与3Sum是相关的题,此题转换成b+c+d = target - a =k的3Sum。

具体方法和思路见如下代码:

public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
int len = nums.length;
if(len <= 3)//长度不足,直接返回
return list;
Arrays.sort(nums);//排序
//开始循环
for(int i = 0; i < len - 2; i++){
//如果target> 0 且nums[i]>target,则剩余数组相加不可能=target
if((target > 0 && nums[i] > target) || (target < 0 && nums[len-1] < target))
break;

if(i > 0 && nums[i] == nums[i-1])//消除重复
continue;

//由a+b+c+d = t 转换成b + c + d = t - a
int a = target - nums[i];
for(int j = i + 1; j < len - 1;j++){
if((a > 0 && nums[j] > a) || (a < 0 && nums[len-1] < a))//如果nums[j]>a,则剩余数组相加不可能=a
break;

if(j > i+1 && nums[j] == nums[j-1])
continue;

int m = j+1;
int n = len - 1;

while(m < n){
int k = nums[j] + nums[m] + nums
;
if(k == a){
List<Integer> al = new ArrayList<Integer>();
al.add(nums[i]);
al.add(nums[j]);
al.add(nums[m]);
al.add(nums
);
list.add(al);
m++;
n--;
while(m < n && nums[m] == nums[m-1])
m++;
while(m < n && nums
== nums[n+1])
n--;
}
else{//分情况改变位置标记
if(k < a)
m++;
else
n--;
}
}
}
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: