[LeetCode] 142.环形链表II
1. 问题描述
2. 实现思路
2.1 自己的思路
~~(一定要写出来啊喂)~
- 受到上一个题哈希表的启发,这个题也可以用哈希表?
时间与空间复杂度都是O(n)
/*
* @lc app=leetcode.cn id=142 lang=csharp
*
* [142] 环形链表 II
*/
var s = new Solution();
s.DetectCycle();
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
// @lc code=start
public class Solution
{
public ListNode DetectCycle(ListNode head)
{
if (head == null) return null;
var h = head;
ISet<ListNode> visited = new HashSet<ListNode>();
while (h.next != null)
{
if (visited.Contains(h)) return h;
visited.Add(h);
h = h.next;
}
return null;
}
}
// @lc code=end
2.2 题解思路
- 判断是否有环:快慢指针相遇
- 判断环的入口:Floyd判圈算法
public class Solution
{
public ListNode DetectCycle(ListNode head)
{
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
if (fast == slow)
{
fast = head;
while (fast != slow)
{
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}
2.3 优化(或者敲一遍题解?)
/*
* @lc app=leetcode.cn id=142 lang=csharp
*
* [142] 环形链表 II
*/
var s = new Solution();
s.DetectCycle();
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x)
{
val = x;
next = null;
}
}
// @lc code=start
public class Solution
{
public ListNode DetectCycle(ListNode head)
{
if (head == null) return null;
var slow = head;
var fast = head;
while (fast != null && fast.next != null)
{
fast = fast.next.next;
slow = slow.next;
if (slow == fast)
{
fast = head;
while (fast != slow)
{
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
return null;
}
}
// @lc code=end

浙公网安备 33010602011771号