-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15. 3Sum Java
More file actions
28 lines (27 loc) · 981 Bytes
/
Copy path15. 3Sum Java
File metadata and controls
28 lines (27 loc) · 981 Bytes
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
import java.util.*;
class Solution {
public <T extends Comparable<T>> List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> output = new ArrayList<List<Integer>>();
int length = nums.length;
Arrays.sort(nums);
int j = 0;
int k = length-1;
for (int i = 0; i < length-2; i++){
j = i + 1;
k = length-1;
if (i > 0 && nums[i] == nums[i-1]){continue;}
if(nums[i]>0){break;}
while(j<k){
if (nums[i]+nums[j]+nums[k] == 0){
List<Integer> temp = Arrays.asList(nums[i], nums[j], (0-nums[i]-nums[j]));
output.add(temp);
while (j < k && nums[j] == nums[j+1]){j++;}
while (j < k && nums[k] == nums[k-1]){k--;}
}
if (nums[i]+nums[j]+nums[k] < 0){j++;}
else{k--;}
}
}
return output;
}
}