Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note: The solution set must not contain duplicate triplets.
For example, given array S = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]思路:第一反应深度优先遍历,但是有重复元素,所以需要排序后每次从非重复元素开始,以其之后的范围的元素为窗口扫描,找出满足题意的三个元素。
时间复杂度:O(N^2)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
Arrays.sort(nums);
for(int a = 0;a<nums.length-2;a++){
if(a==0||nums[a]!=nums[a-1]){//去重
int sum = nums[a];
int l = a+1;
int r = nums.length-1;
while(l<r){
if((sum+nums[l]+nums[r])==0){
list.add(new ArrayList<Integer>(Arrays.asList(nums[a],nums[l],nums[r])));
while(l<r&&nums[l]==nums[l+1])l++;
while(l<r&&nums[r]==nums[r-1])r--;
l++;//多挪一个位置,彻底放弃重复元素
r--;
}else if((sum+nums[l]+nums[r])>0){
r--;
}else{
l++;
}
}
}
}
return list;
}
}