题目地址(142. 环形链表 II)
https://leetcode.cn/problems/linked-list-cycle-ii/
题目描述
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
前置知识
公司
- 暂无
思路
- 方法一:使用HashSet
- 方法二:使用快慢指针,相遇时,再让一个指针从相遇点出发,一个指针从头节点出发(速度一样,每次前进一)。相遇点就是环形位置。这里要注意,快慢指针同时从head出发
关键点
代码
- 语言支持:Java
Java Code:
/**
* 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) {
if (head == null) {
return null;
}
Set<ListNode> posSet = new HashSet<>();
ListNode current = head;
while (current != null) {
if (posSet.contains(current) ) {
return current;
} else {
posSet.add(current);
}
current = current.next;
}
return null;
}
}
复杂度分析
令 n 为数组长度。
- 时间复杂度:
- 空间复杂度:
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null) {
slow = slow.next;
if (fast.next == null) {
return null;
}
fast = fast.next.next;
if (slow == fast) {
ListNode start = head;
while (start != slow) {
slow = slow.next;
start = start.next;
}
return start;
}
}
return null;
}
复杂度分析
令 n 为数组长度。
- 时间复杂度:
- 空间复杂度:
Go语言
func detectCycle(head *ListNode) *ListNode {
if head == nil {
return nil
}
// 这里map的使用,以及空数据的使用struct{}{}
visited := map[*ListNode]struct{}{}
for head != nil {
// 这里使用分号
if _, ok := visited[head]; ok {
return head
}
visited[head] = struct{}{}
head = head.Next
}
return nil
}
网友评论