File tree Expand file tree Collapse file tree 1 file changed +28
-2
lines changed
Expand file tree Collapse file tree 1 file changed +28
-2
lines changed Original file line number Diff line number Diff line change 11/*
2- # Time Complexity: O(n^2 * logn )
2+ # Time Complexity: O(n^2)
33# Space Complexity: O(1)
44*/
55
66class Solution {
7- public List <List <Integer >> threeSum (int [] nums ) {
7+ public List <List <Integer >> threeSum1 (int [] nums ) { // solution 1
88 int n = nums .length ;
99 Arrays .sort (nums );
1010 Set <List <Integer >> ans = new HashSet <>();
@@ -34,4 +34,30 @@ public List<List<Integer>> threeSum(int[] nums) {
3434
3535 return new ArrayList <>(ans );
3636 }
37+
38+ public List <List <Integer >> threeSum (int [] nums ) { // solution 2
39+ int n = nums .length ;
40+ Arrays .sort (nums );
41+ Set <List <Integer >> ans = new HashSet <>();
42+
43+ for (int i = 0 ; i < n - 2 ; i ++) {
44+ int l = i + 1 ;
45+ int r = n - 1 ;
46+ int target = -nums [i ];
47+ while (l < r ) {
48+ int sum = nums [l ] + nums [r ];
49+ if (sum == target ) {
50+ ans .add (new ArrayList <>(Arrays .asList (nums [i ], nums [l ], nums [r ])));
51+ l ++;
52+ r --; // 또 다른 (l, r) 조합이 있을 수 있으므로, loop를 계속 이어간다.
53+ } else if (sum < target ) {
54+ l ++;
55+ } else {
56+ r --;
57+ }
58+ }
59+ }
60+
61+ return new ArrayList <>(ans );
62+ }
3763}
You can’t perform that action at this time.
0 commit comments