题目: 在array中找到所有的组合 a + b + c + d = target , 组合不重复且a < b < c < d
- 数组排序
- 对每一个数组中的元素arr[i] , 求3Sum target = target - arr[i] 时间复杂度 < O(n^3)
- 3Sum暴力的话,时间复杂度为O(n^3) , 但是对于排序的数组,对于 下标 i , j 如果 i < j arr[i] + arr[j] < target , 那么j 之后的元素就不要比较了; 所以,可以设置头尾指针,求3Sum, 如果头+尾 < target , 头+1 ,相反 尾-1 这样时间复杂度为O(n^2)
public static List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> res = new ArrayList<> ();
Arrays.sort(nums);
for(int i = 0 ; i < nums.length;) {
thirdSum(nums , i , target , res);
int t = i;
i++;
for(;i < nums.length && nums[i] == nums[t] ; i++ );
}
return res;
}
private static void thirdSum(int[] nums, int start,
int target, List<List<Integer>> res) {
int len = nums.length;
if(start + 3 >= len) return ;
for(int i = start + 1 ; i <= len - 3; ) {
int head = i + 1;
int tail = len - 1;
int tgt = target - nums[i] - nums[start];
while(head < tail) {
int sum = nums[head] + nums[tail];
if(sum < tgt) {
head++;
} else if (sum > tgt) {
tail--;
} else {
List<Integer> list = new ArrayList<> ();
list.add(nums[start]);
list.add(nums[i]);
list.add(nums[head]);
list.add(nums[tail]);
res.add(list);
int tmp = head;
head++;
for(; head < len && nums[head] == nums[tmp] ; head++);
tmp = tail;
tail--;
for(; tail >= start && nums[tail] == nums[tmp] ; tail--);
}
}
int t = i;
i++;
for(;i < nums.length && nums[i] == nums[t] ; i++ );
}
}