Question : 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)
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)
思路:
Note : 这个跟3sum也挺像。 定义一对指针,指向两头。再定义一对指针,指向中间的两个元素。加起来看看跟target比较一下。决定内部指针怎么移动。
用到了Arrays.sort() 方法,该方法是一种改进的快排,时间复杂度最优情况 O(N*logN)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class FourSum {
public ArrayList fourSum (int[] num, int target) {
HashSet rs = new HashSet();
int len = num.length;
Arrays.sort(num);
if(len <= 3) return new ArrayList(rs);
for(int i = 0; i < len-3; i++) {
for(int k = len-1; k > i+2; k--) {
int ab = num[i] + num[k];
int c = target-ab;
int m = i+1;
int n = k-1;
while(m < n) {
int sum = num[m] + num[n];
if(sum == c) {
ArrayList elem = new ArrayList();
elem.add(num[i]);
elem.add(num[m]);
elem.add(num[n]);
elem.add(num[k]);
rs.add(elem);
m++;
n--;
}
else if(sum < c) {
m++;
}
else n--;
}
}
}
return new ArrayList(rs);
}
}