日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

[LeetCode] 142. Linked List Cycle II

發(fā)布時(shí)間:2025/5/22 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] 142. Linked List Cycle II 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Given a linked list, return the node where the cycle begins. If there is no cycle, return?null.

題意:找一個(gè)鏈表中是否含有環(huán),如果沒有則返回null,如果有則返回環(huán)的起點(diǎn)

我的解法,投機(jī)取巧了,我改了val的值,再次掃到我改的那個(gè)值就是要的節(jié)點(diǎn)

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

二次做這個(gè)題,其實(shí)是做287的時(shí)候,發(fā)現(xiàn)他們說(shuō)是這個(gè)題的變種,我特意回來(lái)重做了一遍

就是用一個(gè)慢指針和一個(gè)快指針,快指針是慢指針的兩倍,他們相遇的時(shí)候(因?yàn)橛协h(huán)的話一定會(huì)相遇。沒有相遇證明沒有)

將slow或者fast指針指向頭,然后步速都變?yōu)?;他們?cè)俅蜗嘤龅臅r(shí)候就是環(huán)的入口;

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

?

補(bǔ)充:這個(gè)算法可能很難去理解,這么證明我就不寫了(畢竟本人不擅長(zhǎng)畫圖)

有興趣的小伙伴可以去證明一下,或者大家直接將結(jié)論記住吧

轉(zhuǎn)載于:https://www.cnblogs.com/Moriarty-cx/p/9710737.html

總結(jié)

以上是生活随笔為你收集整理的[LeetCode] 142. Linked List Cycle II的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。