问题原始链接 https://leetcode.com/problems/4sum
给定长度为n的整数数组S,找到所有和等于指定值的四个元素。
注意:结果集中不能包含重复的元素组。
例如,给定数组 S = [1, 0, -1, 0, -2, 2],并且 target = 0。
结果集为:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
public class Solution {
public static List<List<Integer>> fourSum(int[] nums, int target) {
if (nums == null || nums.length < 4) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i != 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
if (j != i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int k = j + 1;
int l = nums.length - 1;
while (k < l) {
int sum = nums[i] + nums[j] + nums[k] + nums[l];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[k], nums[l]));
k++;
l--;
while (k < l && nums[k] == nums[k - 1]) {
k++;
}
while (k < l && nums[l] == nums[l + 1]) {
l--;
}
} else if (sum < target) {
k++;
} else {
l--;
}
}
}
}
return result;
}
}