topic142

package
v0.0.0-...-b071cee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2023 License: GPL-3.0 Imports: 2 Imported by: 0

README

环形链表II

1. 题目描述

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

说明:不允许修改给定的链表。

进阶: 你是否可以使用 O(1) 空间解决此题?

2. 示例

示例1 1

输入:head = [3,2,0,-4], pos = 1
输出:返回索引为 1 的链表节点
解释:链表中有一个环,其尾部连接到第二个节点。

示例2 2

输入:head = [1,2], pos = 0
输出:返回索引为 0 的链表节点
解释:链表中有一个环,其尾部连接到第一个节点。

示例3 3

输入:head = [1], pos = -1
输出:返回 null
解释:链表中没有环。

提示

  • 链表中节点的数目范围在范围 $[0, 10^4]$ 内
  • $-10^5 <= Node.val <= 10^5$
  • pos 的值为 -1 或者链表中的一个有效索引

3. 解题

同上一题,双指针法.
本题关键在于如何确定入环的第一个节点
设经过x步后,快指针追上慢指针,快指针每次走两步,慢指针每次走一步,若环的节点数为c,则相遇时必有: $$2x-x=c -> x=c$$
因此,当经过x步后相遇,则环的长度为x. 且此时慢指针必未走完环的全程。

设不循环链表段的长度为a,慢指针已走过的环的路程为b,则相遇时慢指针的路程为a+b = c
也即,慢指针要想走完环的全程返回入环处,需走c-b = a步。
因此,在相遇后,我们使用另一个指针从头节点出发,与慢指针同时向前,当二者相遇,此处即为入环处。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ListNode

type ListNode struct {
	Val  int
	Next *ListNode
}

func BuildCircleListWithNoHead

func BuildCircleListWithNoHead(list []int, cursor int) *ListNode

BuildCircleListWithNoHead build a circle list, which tail point to list[cursor]

func BuildListWithHead

func BuildListWithHead(data []int) *ListNode

func BuildListWithNoHead

func BuildListWithNoHead(nums []int) *ListNode

func (*ListNode) Index

func (l *ListNode) Index(target int) *ListNode

func (*ListNode) Slice

func (l *ListNode) Slice() []int

func (*ListNode) String

func (l *ListNode) String() string

func (*ListNode) Tail

func (l *ListNode) Tail() *ListNode

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL