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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值