Created
March 13, 2021 02:23
-
-
Save liyunrui/5f3ea0fb82ced8f0c2619e4801b533bf to your computer and use it in GitHub Desktop.
leetcode-LL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution: | |
def hasCycle(self, head: ListNode) -> bool: | |
""" | |
T:O(n) If there's no cycle, apparently, it's O(n). If there's cycle, O(N+K), N is non-cyclic length and K is alsmot cyclic lengh, in total is O(n). | |
---xxxxx | |
K comes from how many iterations we needed for xxxx==it's logest distance between 2 runners / difference of speed. So, it's almost K/1 | |
""" | |
return self.detect_cycle(head) | |
def detect_cycle(self, head): | |
if not head: | |
return False | |
s = f = head | |
while f and f.next: | |
s = s.next | |
f = f.next.next | |
if s==f: | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment