给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
双指针
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
int len = nums.length;
//前提判断
if (nums == null || len < 3) return res;
//排序(nlogn)
Arrays.sort(nums);
for (int i = 0; i < len - 2; i++) {
if(nums[i] > 0) return res;
//重复情况排除
if (i != 0 && nums[i] == nums[i -1]) continue;
int head = i + 1, tail = len - 1;
while (head < tail) {
int s = nums[i] + nums[head] + nums[tail];
if(s < 0) {
//排除重复项
while(head < tail && nums[head] == nums[++head]);
} else if (s > 0) {
//排除重复项
while(head < tail && nums[tail] == nums[--tail]);
} else {
res.add(new ArrayList<>(Arrays.asList(nums[i], nums[tail], nums[head])));
while(head < tail && nums[head] == nums[++head]) ;
while(head < tail && nums[tail] == nums[--tail]) ;
}
}
}
return res;
}
}
复杂度分析:
- 时间复杂度 O(N^2)
- 空间复杂度 O(1)
https://leetcode-cn.com/problems/3sum/solution/3sumpai-xu-shuang-zhi-zhen-yi-dong-by-jyd/