一,题目描述
二,解题思路
对于本题中的难度在于如何去除重复解。
本题,利用双指针+排序的思想做。
-
特殊值的判定,对于
len
小于3的,一定不存在。 -
对数组首先进行排序。
-
遍历排序后的数组元素:
先“固定” 一个元素(我选择从小到大进行遍历)。然后,定义两个指针lo
,hi
分别扫过后面剩余的元素。
令左指针lo = i + 1
,右指针hi = len - 1
, 当lo < hi
时,执行遍历。- 如果是
nums[lo] + nums[hi] + nums[i] == 0
,执行循环,将数据存入,并将lo
,hi
同时移动位置。 - 如果和大于零,说明
hi
所指元素大,左移。 - 如果和小于零,说明
lo
所指元素小,右移。
- 如果是
三,代码
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
Set<List<Integer>> ans = new HashSet<>();
int len = nums.length;
for(int i = 0; i < len; i++){
int lo = i + 1, hi = len - 1;
while(lo < hi){
if(nums[i] + nums[lo] + nums[hi] == 0){
ans.add(Arrays.asList(nums[i], nums[lo], nums[hi]));
lo++;
hi--;
}else if(nums[i] + nums[lo] + nums[hi] < 0){
lo++;
}else{
hi--;
}
}
}
List<List<Integer>> res = new ArrayList<>();
res.addAll(ans);
return res;
}
}
四,复杂度分析
时间:o(n^2)
空间:o(n)