双指针与滑动窗口中等1 种解法
#18四数之和
返回数组中所有和为 target 且互不重复的四元组。
#数组#排序#双指针
解题主线
01
排序后固定前两个数,后两个数用相向双指针寻找。
02
所有加减法都提升为 long,避免 target 与多个 int 运算时溢出。
解法 1:双重枚举 + 双指针
固定 first、second 后,在右侧有序区间查找和为剩余目标的数对。
时间复杂度
O(n³)
空间复杂度
O(log n),排序栈;不计结果
java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
final class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
int n = nums.length;
for (int first = 0; first + 3 < n; first++) {
if (first > 0 && nums[first] == nums[first - 1]) continue;
for (int second = first + 1; second + 2 < n; second++) {
if (second > first + 1 && nums[second] == nums[second - 1]) continue;
long remaining = (long) target - nums[first] - nums[second];
int left = second + 1;
int right = n - 1;
while (left < right) {
long pair = (long) nums[left] + nums[right];
if (pair < remaining) {
left++;
} else if (pair > remaining) {
right--;
} else {
result.add(List.of(nums[first], nums[second], nums[left], nums[right]));
int leftValue = nums[left];
int rightValue = nums[right];
while (left < right && nums[left] == leftValue) left++;
while (left < right && nums[right] == rightValue) right--;
}
}
}
}
return result;
}
}固定 first、second 后,在右侧有序区间查找和为剩余目标的数对。
边界与易错点
- 四层位置都必须正确去重。
- 依赖 target 符号的简单剪枝并不普适;应使用有序边界和或不剪枝。
整理来源
由旧仓库源码复核、去重并整理;展示代码已按 Java 21 语义修正明显问题。
medium/Q018_fourSum.java