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: 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] ]
Subscribe to see which companies asked this question
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* @author Mouse
*
*/
public class Solution {
public static List<List<Integer>> fourSum(int[] nums, int target) {// nums={1,0,-1,0,-2,2}
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length < 4)
return result;
Arrays.sort(nums);// 对数组进行排序
for (int i = 0; i < nums.length - 3; i++) {// 第一个加数
if (i > 0 && nums[i] == nums[i - 1]) {// 第一个加数使用不重复
continue;
}
for (int j = nums.length - 1; j > i + 2; j--) {// 第四个加数
if (j < nums.length - 1 && nums[j] == nums[j + 1]) {// 第四个加数使用不重复
continue;
}
int start = i + 1;// 第二个加数
int end = j - 1;// 第三个加数
int n = target - (nums[i] + nums[j]);
while (start < end) {
if (nums[start] + nums[end] == n) {
List<Integer> four = new ArrayList<>(4);
four.add(nums[i]);
four.add(nums[start]);
four.add(nums[end]);
four.add(nums[j]);
result.add(four);
while (start < end && nums[start + 1] == nums[start])
start++;
start++;
while (start < end && nums[end] == nums[end - 1])
end--;
end--;
} else if (nums[start] + nums[end] < n) {// 偏小,start往后移
start++;
} else {// 偏大,end往前移
end--;
}
}
}
}
return result;
}
public static void main(String[] args) {
// { -1, 2, 2, -5, 0, -1, 4 }
// { 1, 0, -1, 0, -2, 2 }
// {-5,5,4,-3,0,0,4,-2}
int[] nums = { -5, 5, 4, -3, 0, 0, 4, -2 };
List<List<Integer>> four = fourSum(nums, 4);
System.out.println(four);
}
}