【LeetCode】141 Linked List Cycle (java实现)
来源:互联网 发布:淘宝信用贷款在哪里查 编辑:程序博客网 时间:2024/05/16 02:57
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题目很明确,给定一个链表,判断其中是否包含一个环路。有个额外的要求就是不使用额外的空间。
假如说没有这个额外的要求,有什么方法可以解决呢?创建一个哈希表,遍历链表中的每个元素,并将其假如哈希表中,加入哈希表之前判断是否已经存在于哈希表中,如果存在,则说明存在环,否则就是不存在环。但是,这个哈希表却占用了O(n)的空间,因此该思路不符合要求。
这里,我们可以使用快慢引用的思路。两个引用都指向链表头,从链表头开始遍历,慢引用每次前进一步,而快引用每次前进两步,如果链表是有环路的,那么快引用终将追上慢引用;如果没有环路,那么遍历就会有结束的时候。代码如下:
public class Solution { public boolean hasCycle(ListNode head) { if (head == null) return false; ListNode slow = head, fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; }}
0 0
- 【LeetCode】141 Linked List Cycle (java实现)
- leetcode linked-list-cycle(i 、ii)(java实现)
- LeetCode 141 -Linked List Cycle ( JAVA )
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- [Leetcode] Linked List Cycle (Java)
- [LeetCode][Java] Linked List Cycle
- 【LeetCode-面试算法经典-Java实现】【141-Linked List Cycle(单链表中有环)】
- LeetCode 141 Linked List Cycle(链表判环)
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [leetcode 141] Linked List Cycle
- [leetcode]141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- leetcode || 141、Linked List Cycle
- Leetcode[141]-Linked List Cycle
- leetcode-141-Linked List Cycle
- rtp丢包重传demo
- 创建层次二叉树
- 黑马程序员——多线程10:多线程相关练习
- iOS中定义成员变量时@property(nonatomic, copy/strong/assign/weak)小结
- ADO对SQL Server 2008数据库的基础操作
- 【LeetCode】141 Linked List Cycle (java实现)
- IOS-开发日志-UITextField属性
- 发送邮件代码
- Qt剪贴板复制失败的问题。
- 放苹果
- 【poj1011】木棒
- 【索引】Chapter 5. Graph Theory
- android:数据的存储与访问----文件方法
- java的自动装箱和拆箱