给定一个包含 n 个整数的数组 nums
和一个目标值 target
,判断 nums
中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target
相等?找出所有满足条件且不重复的四元组。
注意:
答案中不可以包含重复的四元组。
示例:
给定数组 nums = [1, 0, -1, 0, -2, 2],和 target = 0。 满足要求的四元组集合为: [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2] ]
package leetCode_5_8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author : caoguotao
* @date 创建时间:2019年5月9日 上午10:34:02
* @version 1.0
* @parameter
* @since
* @return
*/
public class Solution18 {
public static void main(String[] args) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
lists = fourSum(new int[]{1, 0, -1, 0, -2, 2}, 0);
for (List<Integer> list : lists) {
System.out.println(list.get(0) + " " + list.get(1) + " " +
list.get(2) + " " + list.get(3));
}
}
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> lists = new ArrayList<List<Integer>>();
Set<List<Integer>> set = new HashSet<List<Integer>>();
Arrays.sort(nums);
for(int i = 0; i < nums.length - 3; i++) {
for(int j = i + 1; j < nums.length - 2; j++) {
int first = j + 1;
int end = nums.length - 1;
while(first < end) {
int sum = nums[i] + nums[j] + nums[first] + nums[end];
List<Integer> list = new ArrayList<Integer>();
if(sum == target) {
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[first]);
list.add(nums[end]);
set.add(list);
first++;
}
if(sum > target) {
end--;
}
if(sum < target) {
first++;
}
}
}
}
for (List<Integer> list2 : set) {
lists.add(list2);
}
return lists;
}
}