題目
給定一個包含 n 個整數(shù)的數(shù)組 nums,判斷 nums 中是否存在三個元素 a癞蚕,b壕吹,c 著蛙,使得 a + b + c = 0 ?找出所有滿足條件且不重復的三元組耳贬。
注意:答案中不可以包含重復的三元組踏堡。
例如, 給定數(shù)組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合為:
[
[-1, 0, 1],
[-1, -1, 2]
]
思路
- 先將數(shù)組排序咒劲,將三數(shù)之和轉化為兩數(shù)之和
- 跳過滿足條件的重復組
- 找到目標數(shù)組后也需要判斷重復
核心代碼
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;
}
}