Conversation
hayashi-ay
reviewed
Mar 22, 2024
| # step1 | ||
|
|
||
| set を使用した space complexity O(N)の方法はすぐに思いつく. | ||
| 問題は O(1)の場合. Floyd のアルゴリズムで, 合流までの回数などを用いて計算すれば求まりそうだが, あまり自明ではないだろう. Brent のアルゴリズムを使えば求められるだろうが, これも常識の範囲には入らず, 読むには負荷がかかるのではないだろうか. |
There was a problem hiding this comment.
Brent’s Cycle Detection Algorithmは自分は知らなかったです。
There was a problem hiding this comment.
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
def find_cycle_length(start_node):
power = 1
length = 0
slow = start_node
fast = start_node
while fast:
fast = fast.next
length += 1
if slow == fast:
return length
if length == power:
power *= 2
length = 0
slow = fast
return -1
def step_node_by_n(node, n):
while n > 0:
node = node.next
n -= 1
return node
cycle_length = find_cycle_length(head)
if cycle_length == -1:
return None
# 開始点と開始点からcycle_lengthだけ動いた位置から1つずつポインターを進めて合流地点がループの開始地点になる
p1 = head
p2 = step_node_by_n(head, cycle_length)
while p1 != p2:
p1 = p1.next
p2 = p2.next
return p1
Owner
Author
There was a problem hiding this comment.
ありがとうございます!141. Linked List Cycleを解いていたときにこのwikiを見てたまたま知っていたのですが, 勝手にループの開始地点が分かると勘違いしていました. 実装参考になります, Floydのときと同じような形で開始点も見つけられそうなのですね.
|
|
||
| - Google docs の sample answer | ||
| - https://discord.com/channels/1084280443945353267/1195700948786491403/1196010117120925777 | ||
| - キャンベルの法則を知る |
There was a problem hiding this comment.
グッドハートの法則とかも近いですね。こういった法則は博物学的な感じで統一的に何かを説明するものではないですが、名前を知っていることで存在を意識できるようになりますね(ジョシュアツリーの法則)
Owner
Author
There was a problem hiding this comment.
なるほど, ”名前を知ると意識できるようになる”という法則にも名前がついているのですね.
ジョシュアツリーの法則で検索したら他にもいろいろな法則を知ることができました. (https://ktr-05.hatenablog.com/entry/2019/07/07/184436)
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.
Problem link
参照した他の解答についてはnote.mdに記載しております.