Leetcode 142. Linked List Cycle II
方法1: 這題是141的升級版,141是隻要判斷有沒有circle,這題是要先判斷有沒有circle然後再找出這個circle的entry。做法也是一樣,就是歸途賽跑的演算法,只不過這邊有兩個phase。具體思路可以直接看lc官方解答。時間複雜度n,空間複雜度1。
/**
* 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) {
ListNode r = head;
ListNode t = head;
ListNode temp = new ListNode(0);
boolean flag = true;
// phase 1, detect circle and output the intersection node.
while(flag){
if(r == null || r.next == null){
return null;
}
r = r.next.next;
t = t.next;
if(r == t){
flag = false;
temp = r;
}
}
// phase 2, find out the circle entry
ListNode newT = head;
while(newT != temp){
newT = newT.next;
temp = temp.next;
}
return newT;
}
}
總結:
- 要熟悉circle detection演算法
相關文章
- Leetcode Linked List Cycle IILeetCode
- [leetcode]linked-list-cycle-iiLeetCode
- Leetcode-Linked List Cycle IILeetCode
- 【Leetcode】142.Linked List Cycle IILeetCode
- LeetCode142:Linked List Cycle IILeetCode
- leetcode Linked List CycleLeetCode
- LeetCode | 141 linked list cycleLeetCode
- 【Leetcode】141. Linked List CycleLeetCode
- LeetCode141:Linked List CycleLeetCode
- leetcode141: Linked List CycleLeetCode
- Linked List Cycle leetcode II java (尋找連結串列環的入口)LeetCodeJava
- Leetcode Reverse Linked List IILeetCode
- Leetcode-Reverse Linked List IILeetCode
- Reverse Linked List II leetcode javaLeetCodeJava
- Linked List Cycle leetcode java (連結串列檢測環)LeetCodeJava
- 92. Reverse Linked List II
- 資料結構與演算法 | Leetcode 141:Linked List Cycle資料結構演算法LeetCode
- LeetCode Delete Node in a Linked ListLeetCodedelete
- Leetcode Palindrome Linked ListLeetCode
- LeetCode 之 JavaScript 解答第141題 —— 環形連結串列 I(Linked List Cycle I)LeetCodeJavaScript
- 每天一道LeetCode--141.Linked List Cycle(連結串列環問題)LeetCode
- LeetCode 382 Linked List Random NodeLeetCoderandom
- LeetCode-Palindrome Linked ListLeetCode
- LeetCode-Linked List Random NodeLeetCoderandom
- LeetCode-Odd Even Linked ListLeetCode
- leetcode刷題--Reverse Linked ListLeetCode
- 每日leetcode——142. 環形連結串列 IILeetCode
- [LeetCode] 328. Odd Even Linked ListLeetCode
- 【LeetCode】Flatten Binary Tree to Linked ListLeetCode
- Leetcode Flatten Binary Tree to Linked ListLeetCode
- leetcode刷題--Remove Linked List ElementsLeetCodeREM
- LeetCode之Odd Even Linked List(Kotlin)LeetCodeKotlin
- LeetCode | 203. Remove Linked List ElementsLeetCodeREM
- Leetcode 234. Palindrome Linked ListLeetCode
- Leetcode 203. Remove Linked List ElementsLeetCodeREM
- Leetcode-Flatten Binary Tree to Linked ListLeetCode
- Flatten Binary Tree to Linked List leetcode javaLeetCodeJava
- [LeetCode] 2487. Remove Nodes From Linked ListLeetCodeREM