题目
给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路
- 先将数组排序,将三数之和转化为两数之和
- 跳过满足条件的重复组
- 找到目标数组后也需要判断重复
核心代码
if (i > 0 && nums[i] == nums[i - 1]) continue;//跳过重复的
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;//跳过重复的
int low = i + 1, high = nums.length - 1, sum = 0 - nums[i];
while (low < high) {
if (nums[low] + nums[high] == sum) {
res.add(Arrays.asList(nums[i], nums[low], nums[high]));
while (low < high && nums[low] == nums[low + 1]) low++;//去掉重复的
while (low < high && nums[high] == nums[high - 1]) high--;//去掉重复的
low++;
high--;
} else if (nums[low] + nums[high] < sum) {
low++;
} else high--;
}
}
return res;
}
}