-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreeSum.java
More file actions
44 lines (37 loc) · 1.12 KB
/
threeSum.java
File metadata and controls
44 lines (37 loc) · 1.12 KB
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
44
import java.util.*;
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
if (nums.length < 3){
return new ArrayList<>();
}
Set<List<Integer>> result = new HashSet<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length - 2; i++){
int j = i+1;
int k =nums.length - 1;
while(j<k){
int sum = nums[i] + nums[j] + nums[k];
List <Integer> list = new ArrayList<>();
if (sum == 0){
list.add(nums[i]);
list.add(nums[j]);
list.add(nums[k]);
j++;
k--;
result.add(list);
} else if (sum > 0){
k--;
} else {
j++;
}
}
}
return new ArrayList<List<Integer>>(result);
}
public static void main (String[] args){
Solution solution = new Solution();
int[] nums = {-1,0,1,2,-1,-4};
List<List<Integer>> result = solution.threeSum(nums);
System.out.println(result);
}
}