File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*;
2
+ import java .util .stream .Collectors ;
3
+
4
+ class Solution {
5
+ public List <List <Integer >> threeSum (int [] nums ) {
6
+ Map <Integer , Integer > map = new HashMap <>();
7
+ for (int i = 0 ; i < nums .length ; i ++) {
8
+ map .put (nums [i ], i );
9
+ }
10
+
11
+ Set <Triplet > set = new HashSet <>();
12
+ for (int i = 0 ; i < nums .length ; i ++) {
13
+ int target = -nums [i ];
14
+ for (int j = i +1 ; j < nums .length ; j ++) {
15
+ int operand = target - nums [j ];
16
+ if (map .containsKey (operand ) && map .get (operand ) > j ) {
17
+ set .add (new Triplet (nums [i ], nums [j ], operand ));
18
+ }
19
+ }
20
+ }
21
+
22
+ return set .stream ().map (t -> List .of (t .triplet [0 ], t .triplet [1 ], t .triplet [2 ])).collect (Collectors .toList ());
23
+ }
24
+ }
25
+
26
+ class Triplet {
27
+ int [] triplet ;
28
+
29
+ Triplet (int first , int second , int third ) {
30
+ this .triplet = new int [] { first , second , third };
31
+ Arrays .sort (triplet );
32
+ }
33
+
34
+ @ Override
35
+ public boolean equals (Object o ) {
36
+ if (this == o ) return true ;
37
+ if (!(o instanceof Triplet that )) {
38
+ return false ;
39
+ }
40
+
41
+ for (int i = 0 ; i <3 ; i ++) {
42
+ if (this .triplet [i ] != that .triplet [i ]) {
43
+ return false ;
44
+ }
45
+ }
46
+
47
+ return true ;
48
+ }
49
+
50
+ @ Override
51
+ public int hashCode () {
52
+ return Objects .hash (triplet [0 ], triplet [1 ], triplet [2 ]);
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments