您的位置:首页 > 其它

leetcode 18. 4Sum

2016-05-05 17:00 295 查看
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//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)

public class Solution {

public static void main(String[] args) {
int[] a = {-1,2,2,-5,0,-1,4};
List<List<Integer>> result = fourSum(a,3);
for(int i = 0;i<result.size();i++){
System.out.println(result.get(i));
}
}

public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<List<Integer>> result1 = new ArrayList<List<Integer>>();
for(int i = 0;i<nums.length;i++){											//降序排列
for(int j = i+1;j<nums.length;j++){
if(nums[i]<nums[j]){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
}
for(int i = 0;i<nums.length-3;i++){											//确定第一个数,后面三个数使用3sum程序
if(i>0&&nums[i] == nums[i-1]) continue;									//若有两个相同则跳过
int[] num = new int[nums.length-i-1];
for(int j = i+1,k=0;j<nums.length;j++,k++){								//取当前数后面的数组
num[k] = nums[j];
}
result = threeSum(num, target-nums[i]);
for(int k = 0;k<result.size();k++){
result.get(k).add(nums[i]);											//将3sum结果加入当前的数,成为4sum结果
}
result1.addAll(result);													//将每个数得到的3sum结果合并
}
return result1;
}

public static List<List<Integer>> threeSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for(int i = 0;i<nums.length-2;i++){										//遍历数组
int j = i+1;
int end = nums.length-1;
if(i>0&&nums[i] == nums[i-1]){
continue;
}
while(j<end){														//从当前元素之后的两头寻找与其之和为0的两个元素
if(nums[i]+nums[j]+nums[end] == target){
List<Integer> a = new ArrayList<Integer>();
a.add(nums[i]);
a.add(nums[j]);
a.add(nums[end]);
result.add(a);
while(nums[end-1] == nums[end]&&end>j){						//若有相同元素,则直接跳过
end--;
}
while(nums[j+1] == nums[j]&&j<end){
j++;
}
end--;
j++;
}else if(nums[i]+nums[j]+nums[end]>=target){							//若相加不为0,则根据情况调整两端位置
end--;
}else{
j++;
}
}
}
return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: