For this problem, the best solution is to use two pointers: slow and fast. If they meet at somewhere, there is a cycle.
Solution:
# T:O(n) S:O(1)
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
fast, slow = head, head
while fast and fast.next:
fast, slow = fast.next.next, slow.next
if fast is slow:
return True
return False
Run Time: 76 ms
No comments:
Post a Comment