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

相关推荐
predisw8 分钟前
垃圾收集GC的基本理解
java·jvm·算法
奔跑的乌龟_14 分钟前
L3-040 人生就像一场旅行
数据结构·算法
网络骑士hrg.24 分钟前
题解:洛谷 CF2091E Interesting Ratio
算法
一匹电信狗1 小时前
【数据结构】堆的完整实现
c语言·数据结构·c++·算法·leetcode·排序算法·visual studio
丝瓜蛋汤1 小时前
PCA主成分分析法(最大投影方差,最小重构距离,SVD角度)
人工智能·算法·机器学习
un_fired2 小时前
【leetcode刷题日记】lc.78-子集
算法·leetcode
LIUDAN'S WORLD2 小时前
第 2.3 节: 基于 Python 的关节空间与任务空间控制
人工智能·python·算法
achene_ql2 小时前
缓存置换:用c++实现最不经常使用(LFU)算法
c++·算法·缓存
尽兴-2 小时前
缓存分片哈希 vs 一致性哈希:优缺点、区别对比及适用场景(图示版)
算法·缓存·哈希算法
哈全网络3 小时前
如何使用 DeepSeek 帮助自己的工作?
人工智能·算法·ai编程·ai写作