Skip to content

Instantly share code, notes, and snippets.

@liyunrui
Created March 13, 2021 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liyunrui/5f3ea0fb82ced8f0c2619e4801b533bf to your computer and use it in GitHub Desktop.
Save liyunrui/5f3ea0fb82ced8f0c2619e4801b533bf to your computer and use it in GitHub Desktop.
leetcode-LL
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