您的位置:首页 > 其它

[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)

【思路】

如果本节点
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 it