File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ from typing import Optional
2
+ from unittest import TestCase , main
3
+
4
+
5
+ # Definition for singly-linked list.
6
+ class ListNode :
7
+ def __init__ (self , x ):
8
+ self .val = x
9
+ self .next = None
10
+
11
+
12
+ class Solution :
13
+ def hasCycle (self , head : Optional [ListNode ]) -> bool :
14
+ return self .solve (head )
15
+
16
+ """
17
+ Runtime: 37 ms (Beats 93.02%)
18
+ Time Complexity: O(n)
19
+ > head๋ถํฐ next๊ฐ ์๋ ๋์ ์ ํ์ ์ผ๋ก ์กฐํํ๋ฏ๋ก O(n)
20
+
21
+ Memory: 18.62 (Beats 98.22%)
22
+ Space Complexity: O(1)
23
+ > head๋ฅผ ์ ์ธํ๊ณ ์๋ฌด ๋ณ์๋ ์ฌ์ฉํ์ง ์์์ผ๋ฏ๋ก O(1)
24
+ """
25
+ def solve (self , head : Optional [ListNode ]) -> bool :
26
+ if not head :
27
+ return False
28
+
29
+ while head .next :
30
+ if head .next and head .next .val is None :
31
+ return True
32
+
33
+ head .val = None
34
+ head = head .next
35
+
36
+ return False
37
+
38
+
39
+ class _LeetCodeTestCases (TestCase ):
40
+ def test_1 (self ):
41
+ head = None
42
+ output = False
43
+ self .assertEqual (Solution ().hasCycle (head ), output )
44
+
45
+
46
+ if __name__ == '__main__' :
47
+ main ()
You canโt perform that action at this time.
0 commit comments