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.
Follow up:
Can you solve it without using extra space?
同Leetcode 141 Linked List Cycle
性質:distance from head to 環開始點 == distance from 雙指針相遇的點 to 環開始點
證明:
指針a速度為1 指針b速度為2
記head到環開始處的距離為k,環的周長為r,從環開始處順方向到相遇點的距離為d
則a到相遇點走過的路程為 Sa = k + d, Sb= k + nr + d (n為b多繞的圈數)
取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 }轉載于:https://www.cnblogs.com/lilixu/p/4589910.html
總結
以上是生活随笔為你收集整理的Leetcode 142 Linked List Cycle II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [修复] Firemonkey 使用 D
- 下一篇: java selenium (二) 环境