File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ # Time Complexity: O(n^2 * logn)
3+ # Space Complexity: O(1)
4+ */
5+
6+ class Solution {
7+ public List <List <Integer >> threeSum (int [] nums ) {
8+ int n = nums .length ;
9+ Arrays .sort (nums );
10+ Set <List <Integer >> ans = new HashSet <>();
11+
12+ for (int i = 0 ; i < n - 2 ; i ++) {
13+ for (int j = i + 1 ; j < n - 1 ; j ++) {
14+ int target = -nums [i ] - nums [j ]; // nums[i], nums[j]와 더해서 합이 0이 되기 위해 nums[k]가 가져야하는 값
15+ int k = -1 ;
16+ int l = j + 1 ;
17+ int r = n - 1 ;
18+ while (l <= r ) {
19+ int m = (r - l ) / 2 + l ;
20+ if (nums [m ] == target ) {
21+ k = m ;
22+ break ;
23+ } else if (nums [m ] < target ) {
24+ l = m + 1 ;
25+ } else {
26+ r = m - 1 ;
27+ }
28+ }
29+ if (k != -1 ) { // binary search에서 target을 찾은 경우
30+ ans .add (new ArrayList <>(Arrays .asList (nums [i ], nums [j ], nums [k ])));
31+ }
32+ }
33+ }
34+
35+ return new ArrayList <>(ans );
36+ }
37+ }
You can’t perform that action at this time.
0 commit comments