[LeetCode]Linked List Cycle II
2016-12-02 16:45
302 查看
Question
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
本题难度Medium。有2种算法分别是: 集合法和快慢指针法
1、集合法
【复杂度】
时间 O(N) 空间 O(N)
【思路】
如果本节点
【代码】
2、快慢指针法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
首先声明这个是我抄来的,其次我得说这是目前为止我看到的算法中最具数学的推导,我建议推导时候把图画出来。
当
2s = s + nr
推导出 s = nr
设整个链表长L,环入口点与相遇点距离为a,起点到环入口点的距离为x,则:
x+a = nr = (n-1)r+r = (n-1)r+L-x
推导出 x = (n-1)r+(L-x-a)
【代码】
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
本题难度Medium。有2种算法分别是: 集合法和快慢指针法
1、集合法
【复杂度】
时间 O(N) 空间 O(N)
【思路】
如果本节点
cur在集合内,说明
cur就是环的开始位置,返回
cur;否则考察下一个节点。
【代码】
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { //require Set<ListNode> set=new HashSet<>(); ListNode cur=head; //invariant while(cur!=null){ if(set.contains(cur))return cur; set.add(cur); cur=cur.next; } //ensure return null; } }
2、快慢指针法
【复杂度】
时间 O(N) 空间 O(1)
【思路】
首先声明这个是我抄来的,其次我得说这是目前为止我看到的算法中最具数学的推导,我建议推导时候把图画出来。
当
fast与
slow相遇时,
slow肯定没有遍历完链表,而
fast已经在环内循环了
n圈(
1<=n)。假设
slow走了s步,则
fast走了2s步。设环长为r,则:
2s = s + nr
推导出 s = nr
设整个链表长L,环入口点与相遇点距离为a,起点到环入口点的距离为x,则:
x+a = nr = (n-1)r+r = (n-1)r+L-x
推导出 x = (n-1)r+(L-x-a)
L-x-a为相遇点到环入口点的距离。由此我们可以在
head设立另一个慢指针
slow2,两个慢指针相遇点即为环入口点。
【代码】
public class Solution { public ListNode detectCycle(ListNode head) { //require ListNode fast=head,slow=head,slow2=head; //invariant while(fast!=null&&fast.next!=null){ fast=fast.next.next; slow=slow.next; if(fast==slow){ while(slow2!=slow){ slow2=slow2.next; slow=slow.next; } return slow; } } //ensure return null; } }
相关文章推荐
- LeetCode:Linked List Cycle II
- LeetCode:Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode | Linked List Cycle II
- LeetCode之Linked List Cycle II
- leetcode - Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- [LeetCode] - Linked List Cycle II
- [leetcode]Linked List Cycle II
- LeetCode: Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode]Linked List Cycle II
- [leetcode]Linked List Cycle II
- Leetcode Linked List Cycle II
- leetcode: Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II