# Time : O(n), Space : O(n) classSolution(object): defhasCycle(self, head): visited = set() while head: if head in visited: returnTrue visited.add(head) head = head.next returnFalse
Sol2. 快慢指针
小trick : 如果有环,快指针一定会追上慢指针
1 2 3 4 5 6 7 8 9 10
# Time : O(n), Space : O(1) classSolution(object): defhasCycle(self, head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: returnTrue returnFalse
# Time : O(n), Space : O(n) classSolution(object): defdetectCycle(self, head): visited = set() while head: if head in visited: return head visited.add(head) head = head.next returnNone
Sol2. 快慢指针
小trick : 关于长度的证明,相遇点到交点的距离=起点到交点的距离!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Time : O(n), Space : O(1) classSolution(object): defdetectCycle(self, head): ifnot head: returnNone fast = slow = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: # Detect Cycle fast = head while slow != fast: fast = fast.next slow = slow.next return fast returnNone
但是又要求 Time : O(n), Space : O(1), Input Array Read only,只能考虑其他解法!
(比较难想到)Array里index, value中把value当作”next”的index,就可以把问题转化成了Linked List II
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Time : O(n), Space : O(1) classSolution(object): deffindDuplicate(self, nums): ifnot nums: return0 slow = fast = nums[0] # Start from index 0! whileTrue: slow = nums[slow] fast = nums[nums[fast]] if slow == fast: break fast = nums[0] while fast != slow: fast = nums[fast] slow = nums[slow] return fast