算法(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)

相关推荐
NAGNIP12 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
奔跑的蜗牛ing12 小时前
Vue3 + Element Plus 输入框省略号插件:零侵入式全局解决方案
vue.js·typescript·前端工程化
美团技术团队13 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja17 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下17 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶17 小时前
算法 --- 字符串
算法
博笙困了18 小时前
AcWing学习——差分
c++·算法
NAGNIP18 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP18 小时前
大模型微调框架之LLaMA Factory
算法
echoarts18 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust