一 题目描述
给定一个包含 n 个整数的数组 nums
,判断 nums
中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[
[-1, 0, 1],
[-1, -1, 2]
]
二 解题思路
1.由于这是三个值的运算,所以我们基本思路应该是先拿其中一个值作为target,然后找其他范围内twoSum的值等于target,然后把这三个值放进list列表内,继续遍历,若无则另找一个值作为target,依次类推
2.由于得去重且减少遍历的次数,我们可以先将数组按正序排序,先拿索引0作为target,比较下一个索引的值,如果相同,直接跳过,达到去重的作用,直到我们找到下一个不重复的数字作为target中的第一个数字
3.然后在其他范围内指定左指针和右指针,如果将左右指针twoSum的数与target做对比,如果大于,则右指针向左移动,如果小于,则左指针向右移动。
三 代码实战
public static List<List<Integer>> threeSum(int[] num){
List<List<Integer>> result = new ArrayList<List<Integer>>();
if(num.length<3){
return result;
}
Arrays.sort(num);
for (int i = 0; i < num.length - 1; i++) {
if(i==0||num[i]!=num[i-1]) {
int target = 0 - num[i];
int lowIndex = i + 1;
int highIndex = num.length - 1;
while (lowIndex < highIndex) {
int twoSum = num[lowIndex] + num[highIndex];
if (twoSum == target) {
result.add(Arrays.asList(num[i], num[lowIndex], num[highIndex]));
while (lowIndex<highIndex&&num[lowIndex] == num[lowIndex + 1]) {
lowIndex++;
}
while (lowIndex<highIndex&&num[highIndex] == num[highIndex - 1]) {
highIndex--;
}
lowIndex++;
highIndex--;
} else if (twoSum > target) {
highIndex--;
} else {
lowIndex++;
}
}
}
}
return result;
}