1
+ import java .util .Arrays ;
2
+ import java .util .ArrayList ;
3
+ import java .util .List ;
4
+
5
+ class Solution {
6
+ public List <List <Integer >> threeSum (int [] nums ) {
7
+ Arrays .sort (nums );
8
+ List <List <Integer >> result = new ArrayList <>();
9
+
10
+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
11
+ if (i > 0 && nums [i ] == nums [i - 1 ]) continue ;
12
+
13
+ int left = i + 1 ;
14
+ int right = nums .length - 1 ;
15
+
16
+ while (left < right ) {
17
+ int sum = nums [i ] + nums [left ] + nums [right ];
18
+
19
+ if (sum == 0 ) {
20
+
21
+ // result.add(Arrays.asList(nums[i], nums[left], nums[right]));
22
+ List <Integer > triplet = new ArrayList <>();
23
+ triplet .add (nums [i ]);
24
+ triplet .add (nums [left ]);
25
+ triplet .add (nums [right ]);
26
+
27
+ result .add (triplet );
28
+
29
+ while (left < right && nums [left ] == nums [left + 1 ]) left ++;
30
+ while (left < right && nums [right ] == nums [right - 1 ]) right --;
31
+
32
+ left ++;
33
+ right --;
34
+
35
+ } else if (sum < 0 ) {
36
+ left ++;
37
+ } else {
38
+ right --;
39
+ }
40
+ }
41
+ }
42
+ return result ;
43
+ }
44
+ }
45
+
46
+ /**
47
+ Two pointers - fix 1 and use 2 ptrs
48
+ nums[i] + nums[L] + nums[R] == 0
49
+ no duplicates
50
+
51
+ 1. sort array
52
+ 2. skip repeats
53
+ - nums[i] == nums[i - 1]
54
+ - nums[left] == nums[left + 1]
55
+ - nums[right] == nums[right - 1]
56
+ 3. check if sum == 0
57
+ 4. move L right if sum < 0
58
+ 5. move R left if sum > 0 else
59
+
60
+ List<Integer>: [0, 0, 0]
61
+ List<List<Integer>>: [[0, 0, 0], [-2, -3, 5]]
62
+ nums.length - 2까지만 반복: for no out of bounds
63
+ (last 2 val for left, right each)
64
+ */
0 commit comments