public class FourSum {
public List<List<Integer>> fourSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = nums.length - 1; j > i; j--) {
if (nums[j] < nums[j - 1]) {
int tmp = nums[j];
nums[j] = nums[j - 1];
nums[j - 1] = tmp;
}
}
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < nums.length - 3;) {
for (int j = i + 1; j < nums.length - 2;) {
int tmp = target - nums[i] - nums[j];
int p = j + 1;
int q = nums.length - 1;
while (p < q) {
if (nums[p] + nums[q] == tmp) {
result.add(Arrays.asList(nums[i], nums[j], nums[p], nums[q]));
}
if (nums[p] + nums[q] <= tmp) {
while (p + 1 < q && (nums[p + 1] == nums[p])) {
p++;
}
p++;
}else {
while (q - 1 > p && (nums[q - 1] == nums[q])) {
q--;
}
q--;
}
}
while (j + 1 < nums.length && nums[j] == nums[j + 1]) {
j++;
}
j++;
}
while (i + 1 < nums.length && nums[i] == nums[i + 1]) {
i++;
}
i++;
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{2,2,2,2,2};
FourSum fs = new FourSum();
fs.fourSum(nums, 8);
}
}
可以实现,但不是很好。这是一道双指针的变种,两个指针从两头遍历数组可以有效排除一些组合。