File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import java .util .Arrays ;
2+ import java .util .ArrayList ;
3+ import java .util .List ;
4+
5+ class Solution {
6+ // TC: O(n^2)
7+ // SC: O(1)
8+ public List <List <Integer >> threeSum (int [] nums ) {
9+ List <List <Integer >> answer = new ArrayList <List <Integer >>();
10+
11+ // Sort the array to use two-pointer technique.
12+ Arrays .sort (nums );
13+
14+ // Exclude the last two elements from the loop
15+ // since the two pointers are involved in the iteration.
16+ for (int i = 0 ; i < nums .length - 2 ; i ++) {
17+ if (i - 1 >= 0 && nums [i ] == nums [i - 1 ]) {
18+ // Skip if this number is the same as the previous one,
19+ // so that we can avoid duplicate triplets.
20+ continue ;
21+ }
22+
23+ int left = i + 1 ;
24+ int right = nums .length - 1 ;
25+
26+ while (left < right ) {
27+ int sum = nums [i ] + nums [left ] + nums [right ];
28+ if (sum == 0 ) {
29+ ArrayList <Integer > list = new ArrayList <>(
30+ Arrays .asList (nums [i ], nums [left ], nums [right ]));
31+ answer .add (list );
32+
33+ // According to the problem, we need to avoid duplicate triplets.
34+ // Therefore, this loop is needed.
35+ while (left < right && nums [left ] == nums [left + 1 ]) {
36+ left ++;
37+ }
38+ while (left < right && nums [right ] == nums [right - 1 ]) {
39+ right --;
40+ }
41+
42+ left ++;
43+ right --;
44+ }
45+ if (sum < 0 ) {
46+ left ++;
47+ }
48+ if (sum > 0 ) {
49+ right --;
50+ }
51+ }
52+
53+ }
54+
55+ return answer ;
56+ }
57+ }
You can’t perform that action at this time.
0 commit comments