算法(TS):环形链表

给你一个链表的头节点 head ,判断链表中是否有环。如果链表中存在环 ,则返回 true 。 否则,返回 false 。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。

提示:

  • 链表中节点的数目范围是 0, 104
  • -105 <= Node.val <= 105
  • pos 为 -1 或者链表中的一个 有效索引 。

进阶: 你能用 O(1)(即,常量)内存解决此问题吗?

上述链表有环

解法一

遍历链表,用一个 Set 对象保持链表中的节点,如果在遍历的时候发现 Set 对象中已经存在某个节点,则说明该链表有环

ts 复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function hasCycle(head: ListNode | null): boolean {
    const NodeSet = new WeakSet<ListNode>()

    while(head) {
        if(NodeSet.has(head)) {
            return true
        }

        NodeSet.add(head)
        head = head.next
    }

    return false
};

时间复杂度O(n),空间负责度O(n)

解答二

通过快慢指针。为什么快慢指针能解决这个问题?就好比两个速度不同的人在操场上跑圈,速度快的人在 n 圈之后又能与速度慢的人相遇。

ts 复制代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function hasCycle(head: ListNode | null): boolean {
    let fast = head
    let low = head
    while(fast && fast.next) {
        low = low.next
        fast = fast.next.next

        if(low === fast) {
            return true
        }
    }
    return false
};

时间复杂度O(n),空间负责度O(1)

相关推荐
FYKJ_20104 分钟前
springboot羽毛球场地管理系统00626-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
UIU1141 小时前
递归算法与汉诺塔
c++·学习·算法·c#·递归
FYKJ_20101 小时前
django药饮个性化推荐系统54839-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
濮水大叔6 小时前
Cabloy全栈框架的两个SSR入口:Vona集成式SSR vs Zova独立式SSR
typescript·node.js·全栈
用户979984807186 小时前
200 行代码写一个能跑的 AI Agent:不依赖任何框架,只靠 tool-calling 原理
算法
threerocks6 小时前
【Muse实战】X 流量作战室搭建保姆级教程 - 拥有你自己的运营团队
算法
nyaomaru6 小时前
你的 Type Guard 可能会悄悄地与 TypeScript 类型发生偏移 🔧
后端·typescript
GreenTea6 小时前
深度拆解 ScienceBuddy:如何用“双层递归自进化”构建高可靠科研 Agent Harness
前端·后端·算法
花椒技术6 小时前
2.46 秒生成 5 秒视频:拆解 H3 Max 的模型、推理栈与硬件协同
算法·音视频开发·视频编码
vivo互联网技术7 小时前
ART:妆容迁移框架,重新定义高保真妆容迁移 | ECCV 2026
人工智能·算法·图像识别