Every day a Leetcode
题目来源:142. 环形链表 II
解法1:快慢指针
对于链表找环路的问题,有一个通用的解法——快慢指针(Floyd 判圈法)。
给定两个指针,分别命名为 slow 和 fast,起始位置在链表的开头。
每次 fast 前进两步,slow 前进一步。如果 fast 可以走到尽头,那么说明没有环路;如果 fast 可以无限走下去,那么说明一定有环路,且一定存在一个时刻 slow 和 fast 相遇。
当 slow 和 fast 第一次相遇时,我们将fast 重新移动到链表开头,并让 slow 和 fast 每次都前进一步。当 slow 和 fast 第二次相遇时,相遇的节点即为环路的开始点。
代码:
/*
* @lc app=leetcode.cn id=142 lang=cpp
*
* [142] 环形链表 II
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *fast = head, *slow = head;
// 判断是否存在环路
do
{
if (fast == nullptr || fast->next == nullptr)
return nullptr;
fast = fast->next->next;
slow = slow->next;
} while (fast != slow);
// 如果存在,查找环路节点
fast = head;
while (fast != slow)
{
slow = slow->next;
fast = fast->next;
}
return fast;
}
};
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(N),其中 N 为链表中节点的数目。在最初判断快慢指针是否相遇时,slow 指针走过的距离不会超过链表的总长度;随后寻找入环点时,走过的距离也不会超过链表的总长度。因此,总的执行时间为 O(N) + O(N) = O(N)。
空间复杂度:O(1)。我们只使用了 slow, fast 两个指针。
解法2:哈希
一个非常直观的思路是:我们遍历链表中的每个节点,并将它记录下来;一旦遇到了此前遍历过的节点,就可以判定链表中存在环。借助哈希表可以很方便地实现。
代码:
/*
* @lc app=leetcode.cn id=142 lang=cpp
*
* [142] 环形链表 II
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *p = head;
unordered_set<ListNode *> visited;
while (p != nullptr)
{
if (visited.count(p))
return p;
visited.insert(p);
p = p->next;
}
return nullptr;
}
};
// class Solution
// {
// public:
// ListNode *detectCycle(ListNode *head)
// {
// ListNode *fast = head, *slow = head;
// // 判断是否存在环路
// do
// {
// if (fast == nullptr || fast->next == nullptr)
// return nullptr;
// fast = fast->next->next;
// slow = slow->next;
// } while (fast != slow);
// // 如果存在,查找环路节点
// fast = head;
// while (fast != slow)
// {
// slow = slow->next;
// fast = fast->next;
// }
// return fast;
// }
// };
// @lc code=end
结果:
复杂度分析:
时间复杂度:O(N),其中 N 为链表中节点的数目。我们恰好需要访问链表中的每一个节点。
空间复杂度:O(N),其中 N 为链表中节点的数目。我们需要将链表中的每个节点都保存在哈希表当中。