File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+
3
+ # 해시맵
4
+ # 시간복잡도: O(N^2)
5
+ # 공간복잡도: O(N)
6
+ def threeSum (self , nums : List [int ]) -> List [List [int ]]:
7
+ n = len (nums )
8
+ nums .sort ()
9
+
10
+ check = {}
11
+ for idx , num in enumerate (nums ):
12
+ check [num ] = idx
13
+
14
+ answer = set ()
15
+ for i in range (n - 2 ):
16
+ if nums [i ] > 0 :
17
+ break
18
+ if i > 0 and nums [i ] == nums [i - 1 ]:
19
+ continue
20
+ for j in range (i + 1 , n ):
21
+ target = - (nums [i ] + nums [j ])
22
+ if not check .get (target , None ):
23
+ continue
24
+ if j >= check [target ]:
25
+ continue
26
+
27
+ answer .add ((nums [i ], nums [j ], target ))
28
+
29
+ return list (answer )
30
+
31
+ # 투포인터
32
+ # 시간복잡도: O(N^2)
33
+ # 공간복잡도: O(N)
34
+ def threeSum2 (self , nums : List [int ]) -> List [List [int ]]:
35
+ n = len (nums )
36
+ nums .sort ()
37
+
38
+ answer = set ()
39
+ for i in range (n - 2 ):
40
+ if nums [i ] > 0 :
41
+ break
42
+ if i > 0 and nums [i ] == nums [i - 1 ]:
43
+ continue
44
+ l , r = i + 1 , n - 1
45
+ while l < r :
46
+ if nums [l ] + nums [r ] == - nums [i ]:
47
+ answer .add ((nums [i ], nums [l ], nums [r ]))
48
+ l += 1
49
+ r -= 1
50
+
51
+ if nums [l ] + nums [r ] < - nums [i ]:
52
+ l += 1
53
+
54
+ if nums [l ] + nums [r ] > - nums [i ]:
55
+ r -= 1
56
+
57
+ return list (answer )
You can’t perform that action at this time.
0 commit comments