Skip to content

142. Linked List Cycle II.md #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

Conversation

katataku
Copy link
Owner

@katataku katataku commented Nov 16, 2024

https://leetcode.com/problems/linked-list-cycle-ii/
URLを間違えていたので修正しました。


なにはともあれ、フロイドの循環検出も実装してみる。

- ヘルパー関数を使った方がわかりやすい気がした。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

構造の前後を入れ替えたいときに、
https://discord.com/channels/1084280443945353267/1221030192609493053/1225674901445283860

  • 関数化。
  • Python 独特の文法。
  • 無限ループを使う。

などの方法があります。

def find_meeting_point(head: Optional[ListNode]) -> Optional[ListNode]:
fast = head
slow = head
meeting_node = None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

使っていないですね。

return slow
return None

fast = find_meeting_point(head)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここでの変数名がfastなのはちょっと気になります。まあ好みの範囲かもしれないですが、うさぎが亀に追いついた後は、どちらも1つずつしか進まないのでslow, fastという命名はちょっと違うなという気持ちがあります。

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。たしかに・・・

他の方の書き方を見てみたので、まとめ:

  • node1, node2とやっているパターン
  • from_headという書き方のパターン。
    • 142. Linked List Cycle II colorbox/leetcode#18
    • from_headと合わせるなら、from_meeting_pointにするとbetterかと思った。とはいえ、slowが一歩づつというのは変わっていない情報なので、あまりこだわらなくていいかも。

Comment on lines +53 to +58
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if slow == fast:
return slow
return None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whileの条件分岐はfastを使っていてnodeの更新もfastからするなら、ifの条件の左辺をfastにしてreturnで返す値もfastにしないのかな~と思いました。
処理は全く変わらないですが、なんとなく気になったところです。

Copy link
Owner Author

@katataku katataku Nov 17, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ありがとうございます。言われるまで全く気づきませんでした。。。

以下、自分の調べたメモ:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants