【力扣100】142.环形链表2

添加链接描述

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]:
        # 思路是使用set,如果这个节点在set出现过,记录这个节点,并循环出这个节点的下标
        if head is None or head.next is None:
            return None
        visited=set()
        index=0
        while head:
            if head in visited:
                mynode=head
                return mynode
            visited.add(head)
            head=head.next
        return None

        

思路:

  1. 跟环形链表1不同的是,这道题需要返回的值是成环的第一个元素
  2. 所以选择set记录每一个节点,set的本质是哈希表,查询时间复杂度是O(1)
相关推荐
阿昭L26 分钟前
堆结构与堆排序
数据结构·算法
2***574228 分钟前
人工智能在智能投顾中的算法
人工智能·算法
草莓熊Lotso32 分钟前
《算法闯关指南:动态规划算法--斐波拉契数列模型》--01.第N个泰波拉契数,02.三步问题
开发语言·c++·经验分享·笔记·其他·算法·动态规划
2501_941805311 小时前
智慧零售平台中的多语言语法引擎与实时推荐系统实践
leetcode
mit6.8247 小时前
bfs|栈
算法
CoderYanger8 小时前
优选算法-栈:67.基本计算器Ⅱ
java·开发语言·算法·leetcode·职场和发展·1024程序员节
jllllyuz8 小时前
Matlab实现基于Matrix Pencil算法实现声源信号角度和时间估计
开发语言·算法·matlab
夏鹏今天学习了吗8 小时前
【LeetCode热题100(72/100)】前 K 个高频元素
leetcode
稚辉君.MCA_P8_Java8 小时前
DeepSeek 插入排序
linux·后端·算法·架构·排序算法
多多*8 小时前
Java复习 操作系统原理 计算机网络相关 2025年11月23日
java·开发语言·网络·算法·spring·microsoft·maven