-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path15. 3Sum
28 lines (28 loc) · 991 Bytes
/
15. 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
//O(n2) and O(1)
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList();
if(nums==null || nums.length<3) return list;
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if(i==0 || nums[i]!=nums[i-1]){
int low = i+1, high = nums.length-1;
while(low<high){
int sum = nums[i]+nums[low]+nums[high];
if(sum==0){
list.add(Arrays.asList(nums[low],nums[high],nums[i]));
while(low<high && nums[low]==nums[low+1]) low++;
while(low<high && nums[high]==nums[high-1]) high--;
low++;
high--;
}
else if(sum>0)
high--;
else
low++;
}
}
}
return list;
}
}