- 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
示例 1:
输入:nums = [-1,0,1,2,-1,-4]
输出:[[-1,-1,2],[-1,0,1]]
示例 2:
输入:nums = []
输出:[]
示例 3:
输入:nums = [0]
输出:[]
代码:
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
/**
* 三指针解法:
* 1、数组排序
* 2、中间指针作为校验
* 3、两边指针的值相加,大于中间指针值的相反数则移动右指针,反之移动左指针
* 4、移动左或者右指针时,如果与上一次值相同,则继续移动(去重)
* 5、如果相等,则保存三个值,同时移动左右指针
* 6、如果左右指针任意一个与中间指针重叠,则移动中间指针
*/
List<List<Integer>> result = new ArrayList<>();
Map<Integer, Integer> checkRepeat = new HashMap<>();
//排序
Arrays.sort(nums);
for (int i = 1; i < nums.length - 1; i++) {
int leftIndex = 0;
int rightIndex = nums.length - 1;
while (leftIndex != i && rightIndex != i){
int first = nums[leftIndex];
int second = nums[i];
int third = nums[rightIndex];
if (first + third == -second) {
leftIndex += 1;
rightIndex -= 1;
//判断重复,三数之中如果有两个数一样,则第三个数也一样
Integer checkValue = checkRepeat.get(first);
if (Integer.valueOf(second).equals(checkValue)){
continue;
}else {
List<Integer> list = new ArrayList<>();
list.add(first);
list.add(second);
list.add(third);
result.add(list);
checkRepeat.put(first, second);
}
}else if (first + third > -second){
rightIndex -= 1;
}else {
leftIndex += 1;
}
}
}
return result;
}
}