-
Notifications
You must be signed in to change notification settings - Fork 0
/
3Sum
43 lines (41 loc) · 1.31 KB
/
3Sum
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
if(nums.length<3 || nums==null) return res;
Arrays.sort(nums);
int k=nums.length-1;
for(int i=0; i<nums.length; i++){
int j=i+1;
if(i>0 && nums[i]==nums[i-1]){
continue;
}
while(j<k){
if(k<nums.length-1 && nums[k]==nums[k+1]){
k--;
continue;
}
if(nums[i]+nums[j]+nums[k]>0){
k--;
}
else if(nums[i]+nums[j]+nums[k]<0){
j++;
}
else{
List<Integer> list=new ArrayList<>();
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
res.add(list);
k--;
j++;
}
}
}
return res;
}
}
#Status: earnt about two pointer trick but could not solve the test case [-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6]
expected output for above:
[[-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2],[-2,-2,4],[-2,0,2]]
got [-4,-2,6],[-4,0,4],[-4,1,3],[-4,2,2]
have to use set for this.