142.linked list cycle ii#2
Open
ntanaka1984 wants to merge 2 commits into
Open
Conversation
maeken4
reviewed
Jul 19, 2025
maeken4
left a comment
There was a problem hiding this comment.
いいと思います!
Setを使った実装が標準的かとは思いますが、ややトリッキーな(思いつけなくてもいい)方法としてフロイトの循環検出アルゴリズムがあります。
コメント集https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.jfs03xpyyrfl
新井さんの解説
https://youtu.be/Oz7-VlcTpSQ
以下私の理解の確認のためにまとめたものですが…
headから速さ2で動くポインタfastと速さ1で動くポインタslowを考える。サイクルがある場合fastとslowはどこかで合流する。
単連結リストのheadを開始点、ループが始まる点を分岐点、fastとslowが合流する点を合流点と呼ぶ。
fastとslowが合流したあと、両者を同じ速さ1(今までのslowの速さ)でそれぞれが今来た道を同じ速さでslowが開始点に戻るまで同時に戻ることにしました。
この動きについて次の二点がわかります。
- slowが分岐点から開始点に向かうタイミングまでslowとfastは一緒に動く。
- 終了時にfastは合流点にいる(合流するまでの間fastはslowの二倍進んでいたため)。
このことから、slowを開始点、fastを合流点におき、それぞれを順方向に速さ1で動かして合流した点が分岐点と分かります。
Owner
Author
|
おおむね図に書いて頂いている内容でよいかと思いますが、合流点までにfastが動いた距離はX+Y+nL(nはfastが閉路を何周したか)になります。具体的にはXが他と比べて十分長い状況です。するとfastが合流点から出発してXだけ進むと、mod Lで分岐点にいることがわかります。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

142.linked list cycle II をStep4 まで完了しました。
問題: https://leetcode.com/problems/linked-list-cycle-ii/description/
言語:C++
お手すきのときにレビュー何卒お願い申し上げます。