Conversation
| - 上記の位置関係を維持したまま、両者を1づつ移動させて再び一致した位置が循環の開始位置 | ||
| ### フロイドの循環検出法 | ||
| ```python | ||
| lass Solution: |
| fast = head | ||
| slow = head | ||
|
|
||
| while (fast and fast.next): |
There was a problem hiding this comment.
括弧いらないですね。以下 if なども同様ですが、他の言語に影響を受けていたりするでしょうか。
There was a problem hiding this comment.
確かにいらないですね…ご指摘ありがとうございます。
| if (fast is None or fast.next is None): | ||
| return None |
There was a problem hiding this comment.
while ... else でも書けますね。Python 特有の書き方ではあると思いますが、while の条件式を繰り返すよりはシンプルかと思います。
| if (fast is slow): | ||
| break | ||
|
|
||
| if (fast is None or fast.next is None): |
There was a problem hiding this comment.
while fast and fast.next との一貫性がないのが気になります。 どの規約でもいいのですが、なにか決めて一貫して準拠したほうがよいかと思います。
https://google.github.io/styleguide/pyguide.html#2144-decision
|
|
||
| return None | ||
| ``` | ||
| * 変数名を `node` から `current_node` に変更して、より分かりやすく |
There was a problem hiding this comment.
コメント集にも何度か言及があると思いますが、current にはあまり情報量がないので node でよいと思います。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.fcs3httrll4l
| return node | ||
| visited_node.add(node) | ||
| node = node.next | ||
| ``` |
There was a problem hiding this comment.
何も return しないと None が返されるため、意図通り動くと思います。一方、読み手にとって分かりやすくするため、 step 2 のように、明示的に return None を返したほうが良いと思います。
142. Linked List Cycle II
問題リンク: https://leetcode.com/problems/linked-list-cycle-ii/
言語: Python
次回予告: 20. Valid Parentheses