Leetcode Linked List Cycle II 理解分析
2014-03-25 12:06
603 查看
题目大意:给一个链表,判断是否有环,若没有,则返回null;否则返回环的起始节点。
这题可以有两种解决办法,一种使用额外空间,另一种则不开辟额外空间。
解法一:使用额外空间
选择Java的HashSet,HashSet底层是通过HashMap实现的。当扫描到一个已经存在的节点时,这个节点就是环的起始点。空间复杂度和时间复杂度都是O(n)。
解法二:不使用额外空间
两个指针p、q,p指针每次走一步,q指针每次走两步,若存在环,则p与q一定会走到同一个节点,否则q一定先走到链表尾。存在环时,假设p、q现指向同一个节点,设环起始点距链表起始点x,设p走过的步数为y,则q走过的步数为2y,假设链表长度为n。
存在公式:(2y-x)-(y-x) = k(n-x);k为常量。
得出y=k(n-x),当k=1时,p、q所在的节点距离环的起始点为(n-2x),由于环的长度为(n-x),所以p或q再向后走x步就到达环的起始节点位置。
有以下代码:
这题可以有两种解决办法,一种使用额外空间,另一种则不开辟额外空间。
解法一:使用额外空间
选择Java的HashSet,HashSet底层是通过HashMap实现的。当扫描到一个已经存在的节点时,这个节点就是环的起始点。空间复杂度和时间复杂度都是O(n)。
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null) return null; HashSet<ListNode> set = new HashSet<ListNode>(); ListNode p = head; while(p != null) { if(set.contains(p) == true) return p; set.add(p); p = p.next; } return null; } }
解法二:不使用额外空间
两个指针p、q,p指针每次走一步,q指针每次走两步,若存在环,则p与q一定会走到同一个节点,否则q一定先走到链表尾。存在环时,假设p、q现指向同一个节点,设环起始点距链表起始点x,设p走过的步数为y,则q走过的步数为2y,假设链表长度为n。
存在公式:(2y-x)-(y-x) = k(n-x);k为常量。
得出y=k(n-x),当k=1时,p、q所在的节点距离环的起始点为(n-2x),由于环的长度为(n-x),所以p或q再向后走x步就到达环的起始节点位置。
有以下代码:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null) return null; ListNode p = head, q = head; while(p.next != null && q.next != null) { p = p.next; q = q.next; if(q.next == null) return null; q = q.next; if(p == q) break; } if(q.next == null) return null; p = head; while(p != q) { p = p.next; q = q.next; } return p; } }
相关文章推荐
- [Leetcode-142] Linked List Cycle II(链表有环详细分析)
- 【算法分析】如何理解快慢指针?判断linked list中是否有环、找到环的起始节点位置。以Leetcode 141. Linked List Cycle, 142. Linked List Cycle II 为例Python实现
- LeetCode Linked List Cycle II 和I 通用算法和优化算法
- LeetCode - Linked List Cycle I &II
- Leetcode Linked List Cycle II
- LeetCode | Linked List Cycle I,II
- Leetcode#142 Linked List Cycle II
- LeetCode:Linked List Cycle && Linked List Cycle II
- LeetCode Linked List Cycle II
- LeetCode-Linked List Cycle II
- Leetcode78: Linked List Cycle II
- [leetcode]Linked List Cycle II @ Python
- [LeetCode]Linked List Cycle II
- 【题解】【链表】【Leetcode】Linked List Cycle II
- LeetCode: Linked List Cycle I & II
- LeetCode-Linked List Cycle II -有环链表-推理
- Leetcode: Linked List Cycle II
- <LeetCode OJ> 141 / 142 Linked List Cycle(I / II)
- LeetCode — Linked List Cycle II 解题报告
- [LeetCode] Linked List Cycle II, Solution