Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [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]
]
package no1_50;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class subject018 {
class Solution {
public List<List<Integer>> fourSum(int[] nums,int target) {
Map<Integer,HashSet<ArrayList<Integer>>> temp = new HashMap<Integer,HashSet<ArrayList<Integer>>>();
ArrayList<Integer> sums = new ArrayList<Integer>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
Set<List<Integer>> result1 = new HashSet<List<Integer>>();
List<ArrayList<Integer>> result0 = new ArrayList<ArrayList<Integer>>();
//Map<String, List<Integer>> res = new HashMap<String, List<Integer>>();
Arrays.sort(nums);
//用一个两重循环计算两两相加和
for(int i=0; i<nums.length; i++) {
for(int j=i+1; j<nums.length; j++) {
int sum = nums[i] + nums[j];
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);
list.add(j);
if(temp.get(sum)!=null) {
temp.get(sum).add(list);
}else {
HashSet<ArrayList<Integer>> set = new HashSet<ArrayList<Integer>>();
set.add(list);
temp.put(sum, set);
sums.add(sum);
}
}
}
Comparator c = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if((int)o1<(int)o2) {
return 1;
}else {
return -1;
}
}
};
Collections.sort(sums, c);
for(int a:sums) {
int b = target - a ;
if(temp.get(b)!=null) {
HashSet<ArrayList<Integer>> setA = temp.get(a);
HashSet<ArrayList<Integer>> setB = temp.get(b);
for(List lista:setA) {
for(List listb:setB) {
HashSet<Integer> setab = new HashSet<Integer>();
ArrayList<Integer> listab = new ArrayList<Integer>();
listab.addAll(lista);
listab.addAll(listb);
Collections.sort(listab);
setab.addAll(listab);
if(setab.size()==4) {//表示数组中每个数字只用一次
//下标转值
ArrayList<Integer> listab2 = new ArrayList<Integer>();
listab2.add(nums[listab.get(0)]);
listab2.add(nums[listab.get(1)]);
listab2.add(nums[listab.get(2)]);
listab2.add(nums[listab.get(3)]);
result1.add(listab2);
}
}
}
}
}
result.addAll(result1);
return result;
}
}
public static void main(String[] args) {
subject018 subject = new subject018();
Solution s = subject.new Solution();
int[] nums = {-9,-2,7,6,-8,5,8,3,-10,-7,8,-8,0,0,1,-8,7};
int target = 4;
List<List<Integer>> result = s.fourSum(nums, target);
System.out.println(result);
}
}