[LeetCode] 142. Linked List Cycle II
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] 142. Linked List Cycle II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given a linked list, return the node where the cycle begins. If there is no cycle, return?null.
題意:找一個鏈表中是否含有環,如果沒有則返回null,如果有則返回環的起點
我的解法,投機取巧了,我改了val的值,再次掃到我改的那個值就是要的節點
public class Solution {public ListNode detectCycle(ListNode head) {ListNode n = head;if(n == null || n.next == null)return null;while(n.next != null) {if(n.val == -3276800)return n;n.val = -3276800;n = n.next;}return null;} }二次做這個題,其實是做287的時候,發現他們說是這個題的變種,我特意回來重做了一遍
就是用一個慢指針和一個快指針,快指針是慢指針的兩倍,他們相遇的時候(因為有環的話一定會相遇。沒有相遇證明沒有)
將slow或者fast指針指向頭,然后步速都變為1;他們再次相遇的時候就是環的入口;
public class Solution {public ListNode detectCycle(ListNode head) {ListNode n = head;if (n == null || n.next == null) return null;ListNode pre = head.next;ListNode nxt = head.next.next;if (pre == null || nxt == null)return null;while (true) {if (pre == nxt) break;if (pre.next == null) return null;pre = pre.next;if (nxt.next == null) return null;nxt = nxt.next;if (nxt.next == null) return null;nxt = nxt.next;}pre = head;while (pre != nxt) {pre = pre.next;nxt = nxt.next;}return pre;} }?
補充:這個算法可能很難去理解,這么證明我就不寫了(畢竟本人不擅長畫圖)
有興趣的小伙伴可以去證明一下,或者大家直接將結論記住吧
轉載于:https://www.cnblogs.com/Moriarty-cx/p/9710737.html
總結
以上是生活随笔為你收集整理的[LeetCode] 142. Linked List Cycle II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中字符串的常见操作方法
- 下一篇: 朱 - 刘算法