package com.app.main.LeetCode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* id = 18
* level = medium
* 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]
* ]
* Created with IDEA
* author:Dingsheng Huang
* Date:2019/9/4
* Time:下午5:50
*/
public class FourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int len = nums.length;
for (int i = 0; i < len - 2; i++) {
if (i > 0 && nums[i] == nums[i-1]) {
continue;
}
for (int j = i + 1; j < len - 2; j++) {
if (j > i + 1 && nums[j] == nums[j-1]) {
continue;
}
int p1 = j + 1;
int p2 = len - 1;
int tempNum = target - (nums[i] + nums[j]);
while (p1 < p2) {
if (tempNum == nums[p1] + nums[p2]) {
List<Integer> tempList = new ArrayList<>();
tempList.add(nums[p1]);
tempList.add(nums[p2]);
tempList.add(nums[i]);
tempList.add(nums[j]);
result.add(tempList);
// 去重
while (p1 < p2 && nums[p1] == nums[p1 + 1]) {
p1++;
}
while (p1 < p2 && nums[p2] == nums[p2 - 1]) {
p2--;
}
p1++;
p2--;
} else if (tempNum > nums[p1] + nums[p2]) {
p1++;
} else {
p2--;
}
}
}
}
return result;
}
}