题目:LCR 007
解法一:排序 + 双指针
求a + b + c = 0
,先排序,然后写一层循环固定a,接着查找a之后的元素,查找条件:b + c = target - a
,这就回到了LCR 006
,区别仅为条件不同
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for (int a = 0; a < nums.length - 2; a++) {
//防重复遍历判断
if (a > 0 && nums[a] == nums[a - 1]) {
continue;
}
//双指针遍历
int b = a + 1, c = nums.length - 1;
while (b < c) {
//防重复遍历判断
if ((b > a + 1 && nums[b] == nums[b - 1])) {
b++;
continue;
}
//防重复遍历判断
if (c < nums.length - 1 && nums[c] == nums[c + 1]) {
c--;
continue;
}
//逻辑设计
int sum = nums[a] + nums[b] + nums[c];
if (sum == 0) {
res.add(Arrays.asList(nums[a], nums[b], nums[c]));
//关键点:不能直接跳出循环,因为在bc范围内可能还存在其他答案
//如:当a=-2时,bc可以为-1、3,也可以为0、2,因此要继续遍历
b++;
c--;
} else if (sum < 0) {
b++;
} else {
c--;
}
}
}
return res;
}
}
难点:3元素组合不能重复。要解决这个问题,只需设计当其他两个元素和上次循环一样时,当前循环项的值不能和上一次循环的值相同即可。
例如:循环a时,若a与上次循环值相同,则又会把上次的abc组合重复录入;循环b和c时,也是同样的道理。因此只需将第一次遇到该循环值时的组合保留即可
双指针:如果我们发现随着第一个元素的递增,第二个元素是递减的,那么就可以使用双指针的方法,将枚举的时间复杂度从 O(N2) 减少至 O(N)
解法二:排序 + 双指针
与解法一一致,只是实现双指针的语句不同
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// 枚举 a
for (int first = 0; first < n; ++first) {
// 需要和上一次枚举的数不相同
if (first > 0 && nums[first] == nums[first - 1]) {
continue;
}
// c 对应的指针初始指向数组的最右端
int third = n - 1;
int target = -nums[first];
// 枚举 b
for (int second = first + 1; second < n; ++second) {
// 需要和上一次枚举的数不相同
if (second > first + 1 && nums[second] == nums[second - 1]) {
continue;
}
// 需要保证 b 的指针在 c 的指针的左侧
while (second < third && nums[second] + nums[third] > target) {
--third;
}
// 如果指针重合,随着 b 后续的增加
// 就不会有满足 a+b+c=0 并且 b<c 的 c 了,可以退出循环
if (second == third) {
break;
}
if (nums[second] + nums[third] == target) {
ans.add(Arrays.asList(nums[first], nums[second], nums[third]));
}
}
}
return ans;
}
}
注意:双指针仅对有序数组有效