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

相关推荐
却话巴山夜雨时i44 分钟前
394. 字符串解码【中等】
java·数据结构·算法·leetcode
haing20191 小时前
使用黄金分割法计算Bezier曲线曲率极值的方法介绍
算法·黄金分割
leoufung1 小时前
LeetCode 230:二叉搜索树中第 K 小的元素 —— 从 Inorder 遍历到 Order Statistic Tree
算法·leetcode·职场和发展
jyyyx的算法博客1 小时前
多模字符串匹配算法 -- 面试题 17.17. 多次搜索
算法
da_vinci_x1 小时前
Sampler AI + 滤波算法:解决 AIGC 贴图“噪点过剩”,构建风格化 PBR 工业管线
人工智能·算法·aigc·材质·贴图·技术美术·游戏美术
惊鸿.Jh1 小时前
503. 下一个更大元素 II
数据结构·算法·leetcode
chao1898441 小时前
MATLAB 实现声纹识别特征提取
人工智能·算法·matlab
zhishidi1 小时前
推荐算法之:GBDT、GBDT LR、XGBoost详细解读与案例实现
人工智能·算法·推荐算法
货拉拉技术1 小时前
货拉拉RAG优化实践:从原始数据到高质量知识库
数据库·算法
AKDreamer_HeXY1 小时前
ABC434E 题解
c++·算法·图论·atcoder