题目地址:https://leetcode-cn.com/problems/linked-list-cycle/
时间复杂度和空间复杂度都是O(n):
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
a = set()
while head:
if head in a:
return True
a.add(head)
head = head.next
return False
双指针(快慢指针),空间复杂度O(1):
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head: return False
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
就这么简单的题目,我都是看了题解,再写个几遍才能完全记住,然后过个一个月又搞忘
傻子我,不过在下次忘记之前再巩固一下,就能记得更长时间了…
没办法,自己傻要接受