題目連結: https://leetcode.cn/problems/linked-list-cycle-ii/description/
題解連結: https://www.programmercarl.com/0142.%E7%8E%AF%E5%BD%A2%E9%93%BE%E8%A1%A8II.html#%E5%85%B6%E4%BB%96%E8%AF%AD%E8%A8%80%E7%89%88%E6%9C%AC
沒做出來😀
知識點1:快慢指標判斷有沒有環
知識點2:用數學公式推匯出從頭節點到環形入口節點的距離x等於快慢指標相遇節點到環形入口節點的距離z
解法2:集合法
很簡單,集合的編碼不熟,所有沒有想到
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: #集合法 visited = set() while head: if head in visited: return head visited.add(head) head = head.next return None