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

OpenFOAM-v2006重叠网格挖洞问题实战:如何手动修复overset代码中的边缘识别缺陷 本文深入探讨了OpenFOAM-v2006中重叠网格挖洞问题的实战解决方案,重点修复overset代码中的边缘识别缺陷。通过逆向工程解析挖洞决策机制,设计最小侵入式的函数override方案,并建立多级验证体系,有效解决了网格挖洞区域覆盖不全的问题,提升了计算流体动力学模拟的准确性和可靠性。 阅读详情

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;
	}
}

 

Python办公自动化:用python-docx打造专业级Word表格边框(附完整代码) 本文深入探讨了如何利用python-docx库精细控制Word表格边框,实现办公自动化。通过解析底层XML结构,提供了通用的`set_cell_border`函数,并附上完整代码,帮助用户轻松打造符合商业规范的专业级表格,提升报告、合同等文档的生成效率与视觉效果。 阅读详情

相关推荐

CMOS传输门实战:如何用模拟开关优化你的电路设计(附常见问题排查)

本文深入探讨了CMOS传输门在电路设计中的实战应用与优化策略。文章从核心参数选型入手,详细分析了导通电阻、电荷注入等关键特性对电路性能的影响,并提供了多路复用器构建、精密电路应用等实战架构。同时,重点分享了PCB布局、电源去耦的工程细节,以及开关不导通、信号失真、高频性能不足等常见问题的系统性排查指南,旨在帮助硬件工程师充分发挥CMOS模拟开关的效能,提升电路设计的可靠性与精度。

js777的博客 451

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

【OpenBMC 系列】4.启动流程 使用qume模拟ast2600-evb

1.安装openbmc适配的qume 2.启动bmc 3.使用bmc web

AiFool的博客 4458

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

缺陷检测:使用PatchCore训练自己的数据集

必须包含有训练图片(无缺陷图片)、测试图片(缺陷图片)和ground_truth,并且ground_truth必须与对应图片的名称相同。同上一篇结果一样,我的输出为原始图片大小,但是不知道是不是因为图片不是正方形的,导致训练结果不好。编写一个脚本,重新规划数据集的路径规则,但是我稍微写复杂了一点,使用了类来操作。第二种(复杂):编写一个自己的Dataset,参考。第一种(简单):将数据集路径规则改成项目中。返回的必须是一个字典类型,可以阅读。本人此次使用的是第一种方法。运行时,参数部分直接输入。

xiaoxTai的博客 6476

基于STM32、HAL库的TLV320AIC3204IRHBR音频接口芯片驱动程序设计

* 开启所有数字部分 */#define TLV320AIC3204_REG_LEFT_HEADPHONE_OUT_VOLUME 0x0C /* 左声道耳机输出音量 */#define TLV320AIC3204_REG_DIGITAL_AUDIO_PATH_CONTROL 0x05 /* 数字音频路径控制 */#define TLV320AIC3204_REG_ANALOG_HP_FILTER_CONTROL 0x34 /* 模拟耳机滤波器控制 *//* 最大音量 */

corlin6688的博客 521

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

【00】虹软2023届校招专场 ,计算机类笔试攻略(笔试考试时间、考察范围、笔试难度 等说明)

虹软科技2023校招笔试攻略:三大岗位类别(算法、算法优化、开发)分别于7月24日进行。题型包括选择题、编程题和问答题,其中算法类题目降低难度,编程题改为LeetCode模式。重点考察数学基础、机器学习、编程能力(C/C++/Python)、数据结构和算法优化等。建议根据投递岗位选择问答题,算法优化类注重系统知识和SIMD优化,开发类侧重多线程等实际应用能力。笔试结果将作为校招offer的重要参考。

程序员,他们想的是什么?他们想的永远都是技术,他们崇尚的也永远都是技术。 276

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

Open3D——RANSAC 三维点云空间直线拟合【2025最新版】

使用RANSAC算法在点云数据中拟合三维空间直线的python代码实现。博客长期更新,本文最新更新时间为:2025年3月23日。

点云侠的博客 7354

企业数字化转型解决方案架构设计:一个五维全景视角

本文系统探讨了企业数字化转型的架构设计框架,提出五维协同模型:企业架构作为战略罗盘,业务架构聚焦价值创造,应用架构实现能力载体,数据架构提供智能燃料,技术架构奠定基础支撑。文章深入分析了各架构域的核心要素、设计原则及相互关系,并指出数字化转型需通过渐进路径,结合战略引领、技术赋能和组织变革,构建有机统一的架构体系。该框架为企业应对数字化复杂性提供了系统性方法论,强调从整体视角实现技术与业务的深度融合。

金牌架构师 1256

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

Python 神经计算实训 实训答案分享

【代码】Python 神经计算实训 实训答案分享。

2403_89314916的博客 346

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

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

willduan的博客 1万+

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

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

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

zhunode的探索 330

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

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
上一篇: 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、付费专栏及课程。

余额充值