1. 题目描述
给你一个包含 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]
输出:[]
提示:
0 <= nums.length <= 3000
-105 <= nums[i] <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/3sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2. 题解
思路:参考官方解答,常规思路是三重循环解决,这里优化点在于第二重循环和第三重循环可以并列进行,一个从左边开始遍历,一个从右往左遍历。
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
//先对数组进行排序
Arrays.sort(nums);
int n = nums.length;
for(int first = 0; first < n; first++){
//过滤重复数字
if(first != 0 && nums[first] == nums[first-1]){
continue;
}
int third = n-1;
int target = -nums[first];
for(int second = first + 1; second < n; second++){
//过滤重复数字
if(second != first + 1 && nums[second] == nums[second-1]){
continue;
}
while(second < third && nums[second] + nums[third] > target){
--third;
}
//此轮没有结果
if(second == third){
break;
}
//此轮有结果
if(nums[second] + nums[third] == target){
List<Integer> list = new ArrayList<>();
list.add(nums[first]);
list.add(nums[second]);
list.add(nums[third]);
res.add(list);
}
}
}
return res;
}
}
时间复杂度:O(n*n);
空间复杂度:O(1),不计入返回值的大小。