【力扣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)
相关推荐
兩尛10 小时前
215. 数组中的第K个最大元素
数据结构·算法·排序算法
9523610 小时前
数据结构-堆
java·数据结构·学习·算法
吃着火锅x唱着歌10 小时前
LeetCode 面试题 16.24.数对和
算法·leetcode·职场和发展
不会编程的小寒10 小时前
数据结构 2.0
数据结构·算法
专注VB编程开发20年10 小时前
图片转矢量图(提取轮廓线条)Potrace:一个基于多边形的位图轮廓矢量化算法(translation)
算法·图片转矢量
Dream it possible!10 小时前
LeetCode 面试经典 150_二叉树层次遍历_二叉树的层平均值(82_637_C++_简单)
c++·leetcode·面试·二叉树
小羊失眠啦.10 小时前
Rust核心库(core)深度解析:无依赖基石的设计与实践
数据库·算法·rust
Wenhao.10 小时前
LeetCode Hot100 每日温度
数据结构·算法·leetcode·golang
吃着火锅x唱着歌10 小时前
LeetCode 1679.K和数对的最大数目
算法·leetcode·职场和发展
im_AMBER10 小时前
Leetcode 57
笔记·学习·算法·leetcode