# 思考失敗 ###### tags : `刷題`、`CMD ouput get` ## HackerRank :::info 判斷一個linked list是否有Cycle exit :::  **正解:** ```python=0 class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: nodes = set() while head: if head in nodes: #print(head) #print(nodes) return True nodes.add(head) head = head.next return False ``` **失敗解法:本來是想說在print(head)的過程中,如果head有cycle的話,會output出"Error - Found cycle in the ListNode,只是實作出來的結果是Time Limit Exceeded,猜測是非環的情況print出來花太多時間"** ```python=0 from contextlib import redirect_stdout class Solution: def hasCycle(self, head: Optional[ListNode]) -> bool: f = io.StringIO() with redirect_stdout(f): print(head) out = f.getvalue() if str(out) == "Error - Found cycle in the ListNode\n": return True else: return False ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up