LeetCode Top 100 Liked Questions 142. Linked List Cycle II (Java版; Medium)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Top 100 Liked Questions 142. Linked List Cycle II (Java版; Medium)相关的知识,希望对你有一定的参考价值。
welcome to my blog
LeetCode Top 100 Liked Questions 142. Linked List Cycle II (Java版; Medium)
题目描述
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed)
in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.
第一次做; 快慢指针; 第一次相遇后让慢指针指向head, 让快指针往后移动一步; 主要是数学证明, 先定义距离: 到head节点需要经过的节点数, 之后就好说了; 不用考虑快指针在环中走了多少圈才和慢指针第一次相遇, 不影响最终的推导
定义距离: 到head节点需要经过的节点数
设环中的节点个数是h
设经过t步后快慢指针第一次相遇, 那么距离满足t = 1 + 2t - kh, k表示快慢指针相遇时快指针走了多少个完整的环; 合并同类项后: t = kn - 1
设环入口节点距离head是m, 那么慢指针从head走m步后抵达入口节点,
快指针从第一次相遇的地方走m步后, 考虑环圈数在内, 此时快指针一共距离head为1+2t-kn+m,代入t=kn-1之后得kn-1+m, 此时可以看出, 如果快指针再多走一步, 距离head就变成了kn+m, 不考虑环在内, 快指针距离head为m, 正好和慢指针在入口节点处相遇!
得证
/*
快慢指针
*/
public class Solution
public ListNode detectCycle(ListNode head)
if(head==null || head.next==null)
return null;
ListNode left=head, right=head.next;
while(left!=right)
if(right==null || right.next==null)
return null;
left = left.next;
right = right.next.next;
right = right.next;
left = head;
while(left!=right)
left= left.next;
right = right.next;
return left;
以上是关于LeetCode Top 100 Liked Questions 142. Linked List Cycle II (Java版; Medium)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Top 100 Liked Questions 85. Maximal Rectangle (Java版; Hard)
LeetCode Top 100 Liked Questions 10.Regular Expression Matching (Java版; Hard)
LeetCode Top 100 Liked Questions 142. Linked List Cycle II (Java版; Medium)
LeetCode Top 100 Liked Questions 98. Validate Binary Search Tree (Java版; Medium)
LeetCode Top 100 Liked Questions 124. Binary Tree Maximum Path Sum (Java版; Hard)