力扣刷题-热题100题-第26题(c++、python)

142. 环形链表 II - 力扣(LeetCode)https://leetcode.cn/problems/linked-list-cycle-ii/?envType=study-plan-v2&envId=top-100-liked

哈希法

c++中有unordered_set,python中有set,作为哈希的集合,遍历链表时,若当前指针在集合中就说明有环,返回当前指针,否则将指针加入集合,最后若是正常退出循环表示没有环,返回NULL。

复制代码
//c++
/**
 * 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) {
        unordered_set<ListNode*> a;
        while(head)
        {
            if(a.count(head))   return head;
            a.insert(head);
            head=head->next;
        }
        return NULL;
    }
};

#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        a=set()
        while(head):
            if head in a:
                return head
            a.add(head)
            head=head.next
        return None

快慢指针

如上图所示,两个指针同时从head出发,一个指针s每次走一步,一个指针f每次走两步。

若有环则有s的两倍是f走的距离,即 2*(a+b)=a+n*(b+c)+b,所以有a=(n-1)(b+c)+c。其中(b+c)是环的大小,可省略则有a=c,所以s与f相遇后,再来一个指针head从头出发,s指针继续一步一步走,两个相遇的地方就是入环的地方。

若无环则有f为NULL。

所以大循环是f是否为NULL,在循环里再去判断是否有环并找到入环的地方。

复制代码
//c++
/**
 * 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) {
        if(!head||!head->next)  return NULL;
        ListNode* f=head;
        ListNode* s=head;
        while(f)
        {
            if(!f->next||!f->next->next)    return NULL;
            f=f->next->next;
            s=s->next;
            if(f==s)
            {
                while(s!=head)
                {
                    s=s->next;
                    head=head->next;
                }
                return s;
            }
        }
        return NULL;
    }
};

#python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if head==None or head.next==None:
            return None
        s=head
        f=head
        while f:
            if f.next==None or f.next.next==None:
                return None
            s=s.next
            f=f.next.next
            if s==f:
                while s!=head:
                    s=s.next
                    head=head.next
                return s
        return None
相关推荐
蓝博AI1 小时前
基于卷积神经网络的眼疾识别系统,resnet50,efficentnet(pytorch框架,python代码)
pytorch·python·cnn
威视锐科技2 小时前
软件定义无线电36
网络·网络协议·算法·fpga开发·架构·信息与通信
牧歌悠悠3 小时前
【Python 算法】动态规划
python·算法·动态规划
JINX的诅咒3 小时前
CORDIC算法:三角函数的硬件加速革命——从数学原理到FPGA实现的超高效计算方案
算法·数学建模·fpga开发·架构·信号处理·硬件加速器
二进制人工智能3 小时前
【QT5 网络编程示例】TCP 通信
网络·c++·qt·tcp/ip
明天不下雨(牛客同名)4 小时前
为什么 ThreadLocalMap 的 key 是弱引用 value是强引用
java·jvm·算法
lisw054 小时前
DeepSeek原生稀疏注意力(Native Sparse Attention, NSA)算法介绍
人工智能·深度学习·算法
Doris Liu.5 小时前
如何检测代码注入(Part 2)
windows·python·安全·网络安全·网络攻击模型
逢生博客5 小时前
阿里 FunASR 开源中文语音识别大模型应用示例(准确率比faster-whisper高)
人工智能·python·语音识别·funasr
噔噔噔噔@5 小时前
软件测试对于整个行业的重要性及必要性
python·单元测试·压力测试