-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path15. 3Sum
80 lines (64 loc) · 1.99 KB
/
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//15. 3Sum
//Solution 1
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> ansSet = new HashSet<>();
for(int i = 0; i < nums.length - 1; i++) {
Set<Integer> set = new HashSet<>();
for(int j = i + 1; j < nums.length; j++) {
List<Integer> temp = new ArrayList<>();
if(set.contains(0 - (nums[i] + nums[j]))) {
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(0 - (nums[i] + nums[j]));
Collections.sort(temp);
ansSet.add(temp);
}
else {
set.add(nums[j]);
}
}
}
List<List<Integer>> ans = new ArrayList<>(ansSet);
return ans;
}
}
//Solution 2
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++) {
if(i > 0 && nums[i] == nums[i - 1]) {
continue;
}
int j = i + 1;
int k = nums.length - 1;
while( j < k) {
int sum = nums[i] + nums[j] + nums[k];
if(sum < 0) {
j++;
}
else if( sum > 0) {
k--;
}
else {
List<Integer> temp = new ArrayList<>();
temp.add(nums[i]);
temp.add(nums[j]);
temp.add(nums[k]);
ans.add(temp);
j++;
k--;
while(j < k && nums[j] == nums[j - 1]) {
j++;
}
while(j < k && nums[k] == nums[k + 1]) {
k--;
}
}
}
}
return ans;
}
}