
方法1: 这题是141的升级版,141是只要判断有没有circle,这题是要先判断有没有circle然后再找出这个circle的entry。做法也是一样,就是归途赛跑的算法,只不过这边有两个phase。具体思路可以直接看lc官方解答。时间复杂度n,空间复杂度1。
/**
* 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) {
ListNode r = head;
ListNode t = head;
ListNode temp = new ListNode(0);
boolean flag = true;
// phase 1, detect circle and output the intersection node.
while(flag){
if(r == null || r.next == null){
return null;
}
r = r.next.next;
t = t.next;
if(r == t){
flag = false;
temp = r;
}
}
// phase 2, find out the circle entry
ListNode newT = head;
while(newT != temp){
newT = newT.next;
temp = temp.next;
}
return newT;
}
}
总结:
- 要熟悉circle detection算法

342

被折叠的 条评论
为什么被折叠?



