Leetcode [141, 142] Linked List Cycle,java解法

谁还攥着旧的类加载器:Metaspace OOM 的元数据记账、类卸载条件与泄漏定位解析 MetaSpace区是JVM内存管理中的关键部分,负责存储类元数据。随着Java 8的推出,MetaSpace取代了PermGen区,但其灵活性也带来了新的挑战,尤其是在动态类加载和频繁类更新的场景下,容易导致MetaSpace内存溢出(OOM)问题。本文探讨了MetaSpace OOM的根本原因,包括类加载器泄漏、内存管理不当和GC效率低下等,并提供了一系列调优策略和解决方案,帮助开发者有效排查和防止此类问题的发生,确保应用程序的稳定性和高可用性。 阅读详情

141 Linked List Cycle 

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Approach #1 Hash Set

public boolean hasCycle(ListNode head) {
    Set<ListNode> nodesSeen = new HashSet<>();
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}

Complexity analysis

  • Time complexity : O(n). We visit each of the nn elements in the list at most once. Adding a node to the hash table costs only O(1)time.

  • Space complexity: O(n). The space depends on the number of elements added to the hash table, which contains at most nn elements. 

Approach #2 Two Pointers

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        // unlike int index in arrays, we now use Listnode as pointers
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast.next != null && fast.next.next != null) {
            if (slow == fast) return true;
            
            slow = slow.next;
            fast = fast.next.next;
        }
        
        return false; 
    }
}

Complexity analysis

  • Time complexity : O(n). Let us denote nn as the total number of nodes in the linked list. To analyze its time complexity, we consider the following two cases separately.

    • List has no cycle:
      The fast pointer reaches the end first and the run time depends on the list's length, which is O(n)O(n).

    • List has a cycle:
      We break down the movement of the slow pointer into two steps, the non-cyclic part and the cyclic part:

      1. The slow pointer takes "non-cyclic length" steps to enter the cycle. At this point, the fast pointer has already reached the cycle. \text{Number of iterations} = \text{non-cyclic length} = NNumber of iterations=non-cyclic length=N

      2. Both pointers are now in the cycle. Consider two runners running in a cycle - the fast runner moves 2 steps while the slow runner moves 1 steps at a time. Since the speed difference is 1, it takes \dfrac{\text{distance between the 2 runners}}{\text{difference of speed}}difference of speeddistance between the 2 runners​ loops for the fast runner to catch up with the slow runner. As the distance is at most "\text{cyclic length K}cyclic length K" and the speed difference is 1, we conclude that
        \text{Number of iterations} = \text{almost}Number of iterations=almost "\text{cyclic length K}cyclic length K".

    Therefore, the worst case time complexity is O(N+K), which is O(n)O(n).

  • Space complexity : O(1). We only use two nodes (slow and fast) so the space complexity is O(1)

 

142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Approach #1 Hash Table

public class Solution {
    public ListNode detectCycle(ListNode head) {
        Set<ListNode> visited = new HashSet<ListNode>();

        ListNode node = head;
        while (node != null) {
            if (visited.contains(node)) {
                return node;
            }
            visited.add(node);
            node = node.next;
        }

        return null;
    }
}

Complexity Analysis

  • Time complexity : O(n)O(n)

    For both cyclic and acyclic inputs, the algorithm must visit each node exactly once. This is transparently obvious for acyclic lists because the nnth node points to null, causing the loop to terminate. For cyclic lists, the if condition will cause the function to return after visiting the nnth node, as it points to some node that is already in visited. In both cases, the number of nodes visited is exactly nn, so the runtime is linear in the number of nodes.

  • Space complexity : O(n)O(n)

    For both cyclic and acyclic inputs, we will need to insert each node into the Set once. The only difference between the two cases is whether we discover that the "last" node points to null or a previously-visited node. Therefore, because the Set will contain nn distinct nodes, the memory footprint is linear in the number of nodes.

Approach #2 Floyd's Tortoise and Hare

public class Solution {
    private ListNode getIntersect(ListNode head) {
        ListNode tortoise = head;
        ListNode hare = head;

        // A fast pointer will either loop around a cycle and meet the slow
        // pointer or reach the `null` at the end of a non-cyclic list.
        while (hare != null && hare.next != null) {
            tortoise = tortoise.next;
            hare = hare.next.next;
            if (tortoise == hare) {
                return tortoise;
            }
        }

        return null;
}

    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }

        // If there is a cycle, the fast/slow pointers will intersect at some
        // node. Otherwise, there is no cycle, so we cannot find an entrance to
        // a cycle.
        ListNode intersect = getIntersect(head);
        if (intersect == null) {
            return null;
        }

        // To find the entrance to the cycle, we have two pointers traverse at
        // the same speed -- one from the front of the list, and the other from
        // the point of intersection.
        ListNode ptr1 = head;
        ListNode ptr2 = intersect;
        while (ptr1 != ptr2) {
            ptr1 = ptr1.next;
            ptr2 = ptr2.next;
        }

        return ptr1;
    }
}

Complexity Analysis

  • Time complexity : O(n)O(n)

    For cyclic lists, hare and tortoise will point to the same node after F+C-hF+C−h iterations, as demonstrated in the proof of correctness. F+C-h \leq F+C = nF+C−h≤F+C=n, so phase 1 runs in O(n) time. Phase 2 runs for F < nF<n iterations, so it also runs in O(n) time.

    For acyclic lists, hare will reach the end of the list in roughly \dfrac{n}{2}2n​iterations, causing the function to return before phase 2. Therefore, regardless of which category of list the algorithm receives, it runs in time linearly proportional to the number of nodes.

  • Space complexity : O(1)

    Floyd's Tortoise and Hare algorithm allocates only pointers, so it runs with constant overall memory usage.

三、 关于链表Linked List

设计一个单链表:

/**
 * A singly linked list with a left sentinel node.
 */
class MyLinkedList {

	/** A very simple node class. */
	private static class Node {
		int val;
		Node next;
	}

	// Predecessor of the first element
	private Node headPred;
	// Predecessor of the tail
	private Node tailPred;
	private int length;

	/** Initialize your data structure here. */
	public MyLinkedList() {
		headPred = new Node();
		tailPred = headPred;
		length = 0;
	}

	/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
	public int get(int index) {
		if ((index < 0) || (index >= length)) {
			return -1;
		}
		return findPred(index).next.val;
	}

	/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
	public void addAtHead(int val) {
		if (length == 0) {
			addAtTail(val);
		} else {
			addAfter(headPred, val);
		}
	}

	/** Append a node of value val to the last element of the linked list. */
	public void addAtTail(int val) {
		addAfter(tailPred, val);
		tailPred = tailPred.next;
	}

	/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
	public void addAtIndex(int index, int val) {
		if (index < 0) {
			addAtHead(val);
		} else if (index == length) {
			addAtTail(val);
		} else if ((index >= 0) && (index < length)) {
			addAfter(findPred(index), val);
		}
	}

	/** Delete the index-th node in the linked list, if the index is valid. */
	public void deleteAtIndex(int index) {
		if ((index >= 0) && (index < length)) {
			Node pred = findPred(index);
			if (index == length - 1) { // Remove last element
				// Move tail to the left
				tailPred = pred;
			}
			pred.next = pred.next.next;
			--length;
		}
	}

	/** Return the predecessor of the index-th node. */
	private Node findPred(int index) {
		Node pred = headPred;
		for (int i = 0; i < index; ++i) {
			pred = pred.next;
		}
		return pred;
	}

	/** Add an element after the given node. */
	private void addAfter(Node pred, int val) {
		Node node = new Node();
		node.val = val;
		node.next = pred.next;
		pred.next = node;
		++length;
	}
}

 

高云FPGA系列教程(7):ARM GPIO外部中断 高云GN1NSR-4C共有16个GPIO,每个GPIO可配置成输入或输出模式,支持中断输入,触发方式可选择:上升沿、下降沿、高电平、低电平触发。中断优先级可通过NVIC进行设置,支持 0-7 级可编程中断优先级。 阅读详情

相关推荐

Ubuntu20.04安装Torque-6.1.2单机版(踩坑篇)

说明:PBS排队系统原先是在Centos7安装使用很顺利,但是有客户需求在Ubuntu20.04上使用,着手在Ubuntu20.04安装上安装的时候发现很多报错,并不能顺利安装,网上查找到的教程,有的说是让放弃转slurm,有的是换源安装,但是安装好的版本很低,有许多bug,不是很好用。经过自己慢慢摸索之后,改了部分配置以及源码之后,能够顺利安装,再次记录一下踩坑心得,与大家一起分享学习。如有问题,欢迎大家来撩。...............

华青水上的博客 8087

LeetCode—linked-list-cycle(检测是否有环)—Java

题目描述:Given a linked list, determine if it has a cycle in it.Follow up:Can you solve it without using extra space?思路解析:这个只需要快慢指针的方法就可以检测是否有环。代码:/** * Definition for singly-linked list. * class ListNo...

Lynn_Baby的博客 394

矢量网络分析仪VNA的校准之SOLT方法

作者:杭州冥鸿电子科技有限公司 邮箱:huanglong@deepelec.com S参数的测量方法有两种,一种是基于扫频测量的原理(VNA),另外一种是基于快沿阶跃响应的原理(TDR)。 下图是VNA的原理框图,主要包括以下部分: (1)激励信号源:提供感兴趣的频率范围内的入射信号; (2)信号分离装置:含功分器和定向耦合器,分离出入射,反射和传输信号; (3)接收机:...

u010018619的博客 2万+

LeetCode----Linked List Cycle

Linked List Cycle Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? 分析: 判断一个链表是否含有环。 使用弗洛伊德循环检测法。时间复杂度为O(n)。 算法详解如下:

whiterbear的专栏 875

RK3568实现蓝牙音箱功能

A2DP旨在通过蓝牙连接传输高质量的立体声音频流。它使用的基本压缩算法是SBC(Sub-Band Coding)来减小音频数据的大小,同时保持高音质,SBC压缩虽然效率较低,但是是必须支持的基本备用方案。A2DP还支持其他高级编解码器,例如AAC、aptX和LDAC,这些编解码器比SBC提供更好的音质,但这些编解码器的支持取决于设备本身的支持情况。注意A2DP协议要与AVRCP协议区分开。A2DP是传输音频的,而AVRCP是用来控制音频的。这里我用到的是RK3568 Android11。

leikko的博客 1174

4、文化遗产数字记录的伦理框架构建

本文探讨了在数字技术快速发展的背景下,如何构建一个伦理框架以指导文化遗产的数字记录工作。文章分析了遗产保护的重要性以及当前面临的挑战,包括气候变化、全球化和技术变革等。同时,结合国际古迹遗址理事会(ICOMOS)的伦理原则和加拿大遗产专业人员协会(CAHP)的行为准则,提出了六个核心伦理类别,并讨论了其在实践中的应用。文章强调,伦理框架不仅有助于提高数字记录的质量和可持续性,还能促进专家合作、保护社区利益并确保数字遗产的长期可访问性。未来需要持续完善这一框架,以应对不断变化的技术和社会环境带来的新挑战。

7h6j5k4l3的博客 96

Linked List Cycle(判断链表是否有环)-python

Given a linked list, determine if it has a cycle in it.解答:定义两个指针分别从链表头部开始,一个指针每次走一步,另一个指针每次走两步,若两个指针所指的值相等,则说明有环,否则没环;要注意指针所指之处是否为空class Solution(object):    def hasCycle(self, head):        """      ...

qq_22179091的博客 1002

配置 SAP Web Dispatcher 的实战指南:打通 SAP Fiori、SAP Gateway 与前端系统的关键一跳

SAP Web Dispatcher 在 Fiori 架构中扮演关键角色,作为统一入口处理 HTTPS 请求、实现安全代理和流量分发。它将分散在不同系统的访问路径统一收口,解决浏览器同源策略限制,集中管理 HTTPS 终止和客户端信息传递。典型配置中,Web Dispatcher 监听 443 端口,根据路径将 OData 请求转发至 Gateway 系统,静态资源请求送至前端服务器。SSL 相关配置(如 PSE 文件)确保安全通信,而路由规则(wdisp/system_xx)决定请求转发目标。实施时需注意

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 101

LeetCode 之 linked-list-cycle【检测链表中是否有环】

题目: Given a linked list, determine if it has a cycle in it.   Follow up:   Can you solve it without using extra space?   思路一:要达到的目的,检测链表中是否有环,首先第一个思路可以是遍历整个链表,并标记访问过的节点,如果重复访问了某个节点,说明该链表中有环。该思路实现简单,...

李滚滚的博客 557

YOLO系列算法改进 | 主干改进篇 | 替换LSKNet主干特征提取网络 | 通过动态调整感受野自适应融合长程上下文,显著提升小目标与复杂背景下的检测精度!

YOLO系列算法改进 | 主干改进篇 | 替换LSKNet主干特征提取网络 | 通过动态调整感受野自适应融合长程上下文,显著提升小目标与复杂背景下的检测精度! (以YOLO26最新目标检测模型为基础,利用LSKNet替代Backbone)

2502_91881744的博客 211

手把手教你学Simulink——基于Simulink的Boost变换器电流模式控制(峰值电流控制)建模示例

本文详细介绍了基于Simulink的Boost变换器峰值电流模式控制建模方法。首先分析了Boost变换器在CCM模式下的工作原理及电流控制优势,重点阐述了斜坡补偿的必要性。通过分步指导搭建Simulink模型,包括主电路、电流采样、RS触发器和电压外环PI控制器等核心模块。仿真验证了系统在启动、负载突变和输入电压跌落等工况下的优异性能,输出电压稳定在48V±0.5V。文章还总结了工程实践要点,并提出了数字实现等扩展方向。该建模方法为电力电子高级控制策略的工程验证提供了有效途径。

MHD0815的博客 248

LeetCode Top 100 Liked Questions 141. Linked List Cycle (Java版; Easy)

welcome to my blog LeetCode Top 100 Liked Questions 141. Linked List Cycle (Java版; Easy) 题目描述 Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we...

littlehaes的博客 179

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

(Leetcode 142)Linked List Cycle (II) (快慢指针详解)

Leetcode141题和142题很相似,都涉及到了快慢指针的算法。快慢指针就是设置两个指针,一个快指针,一个慢指针来达到解题的目的。下面分为以下几个模块来讲解: 解第141题解第142题为什么快指针一定要设置为慢指针的2倍快慢指针的拓展应用 一、Leetcode 141题 题目为:Linked List Cycle Given a linked list, determi

willduan的博客 1万+

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

(Leetcode 142)Linked List Cycle (II) (快慢指针详解)

Leetcode141题和142题很相似,都涉及到了快慢指针的算法。快慢指针就是设置两个指针,一个快指针,一个慢指针来达到解题的目的。下面分为以下几个模块来讲解: 解第141题 解第142题 为什么快指针一定要设置为慢指针的2倍 快慢指针的拓展应用 一、Leetcode 141题 题目为:Linked List Cycle Given a linked list, determine i...

zhunode的探索 330

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

LeetCode-141.142. Linked List Cycle (JAVA)链表找环

LeetCode-141.142. Linked List Cycle (JAVA)链表找环

mine_song的博客 936

LeetCode 141 Linked List Cycle 142 Linked List Cycle II

问题描述: 解答: public class Solution { public boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; } ListNode slow=head;...

susuxuezhang的博客 271

leetcode 141. Linked List Cycle 快慢指针

题意 返回是否有环 解1 // 全部存下来 // Runtime: 3 ms, faster than 19.84% of Java online submissions for Linked List Cycle. //Memory Usage: 39.2 MB, less than 16.56% of Java online submissions for Linked List Cycle. public boolean hasCycle(ListNode head)

1 141

leetcode 142. Linked List Cycle II 龟兔赛跑(循环指针)

上一题 题意 如果有环,找出环第一个出现的节点,如果没有,返回null。 解1 空间O(N) // Runtime: 3 ms, faster than 23.27% of Java online submissions for Linked List Cycle II. //Memory Usage: 39.7 MB, less than 5.94% of Java online submissions for Linked List Cycle II. public ListNo

1 180

LeetCode 142. 环形链表 II(Linked List Cycle II)

142. 环形链表 II 142. Linked List Cycle II 题目描述 给定一个链表,返回链表开始入环的第一个节点。如果链表无环,则返回 null。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。 说明: 不允许修改给定的链表。 LeetCode142. Linked List Cycl...

weixin_30788731的博客 111

【leetcode】142. Linked List Cycle II

第142是第141的一个升级版, Given a linked list, determine if it has a cycle in it. 141要求的是查出是否存在有一个链表的循环; Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

SherryWay的博客 263

LeetCode 142. Linked List Cycle II(快慢指针)

Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, we use an integer pos which represen...

da_kao_la的博客 275

C语言快慢指针,【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked L...

引入快慢指针经常用于链表(linked list)中环(Cycle)相关的问题。LeetCode中对应题目分别是:简介快指针(fast pointer)和慢指针(slow pointer)都从链表的head出发。slow pointer每次移动一格,而快指针每次移动两格。如果快慢指针能相遇,则证明链表中有环;否则如果走到头了依然没有相遇,则没有环。快慢指针的具体代码(C++, Python, Ja...

weixin_36403165的博客 263

【LeetCode-面试算法经典-Java实现】【142-Linked List Cycle II(单链表中有环II)】

【142-Linked List Cycle II(单链表中有环II)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a linked list, return the node where the cycle begins. If there is no cycle, return null.   Follow up:   Can you solve

https://github.com/Wang-Jun-Chao 4410

【LeetCode】142. Linked List Cycle II

Difficulty:medium More:【目录】LeetCode Java实现 Description Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Note:Do not modify the linked list. Follow...

weixin_30677073的博客 121

LeetCode_LinkedList_142. Linked List Cycle II 环形链表 II(C++/Java)【快慢指针】

目录 一,题目描述 英文描述 中文描述 二,解题思路 三,AC代码 C++ Java 四,解题过程 第一博 一,题目描述 英文描述 Given a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be

&再见萤火虫&的博客 247

【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycl...

引入 快慢指针经常用于链表(linked list)中环(Cycle)相关的问题。LeetCode中对应题目分别是: 141. Linked List Cycle 判断linked list中是否有环 142. Linked List Cycle II 找到环的起始节点(entry node)位置。 简介 快指针(fast pointer)和慢指针(slow pointer)都从链表的hea...

weixin_30258027的博客 271
上一篇: Leetcode[217, 136, 349, 202] HashTable 小专题 1 HashSet
下一篇: 亚麻 OA 2019 题目
YuanTheCoder
博客等级 码龄9年 2粉丝 34原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值