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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Leetcode 142 Linked List Cycle II

發(fā)布時間:2025/3/15 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Leetcode 142 Linked List Cycle II 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

Follow up:
Can you solve it without using extra space?

同Leetcode 141 Linked List Cycle

性質(zhì):distance from head to 環(huán)開始點 == distance from 雙指針相遇的點 to 環(huán)開始點

證明:

指針a速度為1 指針b速度為2

記head到環(huán)開始處的距離為k,環(huán)的周長為r,從環(huán)開始處順方向到相遇點的距離為d

則a到相遇點走過的路程為 Sa = k + d, Sb= k + nr + d (n為b多繞的圈數(shù))

取n= 1 時 Sb = k + r + d 同時要滿足 Sa * 2 = Sb

則 d = r - k, Sa = r,?Sb = 2r 滿足條件

顯然 不存在n>1 使得成立的情況

var detectCycle = function(head) {if(!head)return nullvar a = headvar b = headwhile(b.next && b.next.next){b = b.next.nexta = a.nextif(a===b){a = headwhile(a !== b){a = a.nextb = b.next}return a}} return null }

轉(zhuǎn)載于:https://www.cnblogs.com/lilixu/p/4589910.html

總結(jié)

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

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