File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Hashmap Solution:
1
2
import java .util .*;
2
3
3
4
public class Solution {
@@ -26,3 +27,43 @@ public List<List<Integer>> threeSum(int[] nums) {
26
27
return new ArrayList <>(result );
27
28
}
28
29
}
30
+
31
+
32
+ // Two Pointer Solution:
33
+ import java .util .ArrayList ;
34
+ import java .util .Arrays ;
35
+ import java .util .List ;
36
+
37
+ public class Solution {
38
+ public List <List <Integer >> threeSum (int [] nums ) {
39
+ Arrays .sort (nums );
40
+ int n = nums .length ;
41
+ List <List <Integer >> answer = new ArrayList <>();
42
+
43
+ for (int i = 0 ; i < n ; i ++) {
44
+ if (nums [i ] > 0 ) {
45
+ break ;
46
+ }
47
+ if (i > 0 && nums [i ] == nums [i - 1 ]) {
48
+ continue ;
49
+ }
50
+ int lo = i + 1 , hi = n - 1 ;
51
+ while (lo < hi ) {
52
+ int sum = nums [i ] + nums [lo ] + nums [hi ];
53
+ if (sum == 0 ) {
54
+ answer .add (Arrays .asList (nums [i ], nums [lo ], nums [hi ]));
55
+ lo ++;
56
+ hi --;
57
+ while (lo < hi && nums [lo ] == nums [lo - 1 ]) lo ++;
58
+ while (lo < hi && nums [hi ] == nums [hi + 1 ]) hi --;
59
+ } else if (sum < 0 ) {
60
+ lo ++;
61
+ } else {
62
+ hi --;
63
+ }
64
+ }
65
+ }
66
+
67
+ return answer ;
68
+ }
69
+ }
You can’t perform that action at this time.
0 commit comments