File tree Expand file tree Collapse file tree 1 file changed +16
-17
lines changed Expand file tree Collapse file tree 1 file changed +16
-17
lines changed Original file line number Diff line number Diff line change 1
- # 시간복잡도 O(n^2), 공간복잡도 O(n^2)
2
1
class Solution :
3
2
def threeSum (self , nums : List [int ]) -> List [List [int ]]:
4
- # key: 값, value: list((i, j))
5
- dic = {}
6
- answer = set ()
3
+ answerSet = set ()
4
+ nums .sort ()
7
5
8
- # 이중 for문으로 모든 경우의 수를 구합니다.
9
- for i in range (len (nums )):
10
- for j in range (i + 1 , len (nums )):
11
- if nums [i ] + nums [j ] in dic :
12
- dic [nums [i ] + nums [j ]].append ((i , j ))
6
+ for i in range (len (nums ) - 2 ):
7
+ leftIdx = i + 1
8
+ rightIdx = len (nums ) - 1
9
+ while leftIdx < rightIdx :
10
+ sum = nums [i ] + nums [leftIdx ] + nums [rightIdx ]
11
+ if sum < 0 :
12
+ leftIdx += 1
13
+ elif sum > 0 :
14
+ rightIdx -= 1
13
15
else :
14
- dic [nums [i ] + nums [j ]] = [(i , j )]
16
+ answerSet .add ((nums [i ], nums [leftIdx ], nums [rightIdx ]))
17
+ leftIdx = leftIdx + 1
18
+ rightIdx = rightIdx - 1
15
19
16
- for k in range (len (nums )):
17
- for i , j in dic .get (- nums [k ], []):
18
- if i != k and j != k :
19
- answer .add (tuple (sorted ([nums [i ], nums [j ], nums [k ]])))
20
-
21
- return list (answer )
22
-
20
+ return list (answerSet )
21
+
You can’t perform that action at this time.
0 commit comments