15. 三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
两种思路:
1.暴力方法(三重循环):
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
int n = nums.length;
Set result = new HashSet();
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
for(int k = j + 1; k < n; k++){
if(nums[i]+nums[j]+nums[k] == 0){
List result2 = new ArrayList();
result2.add(nums[i]);
result2.add(nums[j]);
result2.add(nums[k]);
Collections.sort(result2);
result.add(result2);
}
}
}
}
return new ArrayList<>(result);
}
}
超出时间限制
2.排序+双指针
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
// 思路:排序+双指针
List<List<Integer>> ans = new ArrayList<List<Integer>>();
int len = nums.length;
// 进行排序
Arrays.sort(nums);
if(nums == null || len < 3)
return ans;
for(int i = 0; i < len; i++){
if(nums[0] > 0) break;
if(i > 0 && nums[i] == nums[i-1]) continue;
int L = i+1;
int R = len-1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[i]);
list.add(nums[L]);
list.add(nums[R]);
ans.add(list);
while(L<R && nums[L] == nums[L+1]) L++;
while(L<R && nums[R] == nums[R-1]) R--;
L++;
R--;
}
else if(sum < 0) L++;
else if(sum > 0) R--;
}
}
return ans;
}
}
遇到的错误:粗心讲R–写为R++ 导致数据越界
#保存三元组用集合:list的元素是各个子集合