Conversation
There was a problem hiding this comment.
全体としてよくかけていると思いました.
fast = slow = headも選択肢でしょうか?
There was a problem hiding this comment.
ありがとうございます。
そうですね、個人的に少し1行に詰め込むと読みづらいと感じる時があるので、この書き方にしています。
There was a problem hiding this comment.
様々な解法をご検討されており,よいと思います.
ほかにも,
・関数を用いる方法(以下の部分で実装されていますが,フロイドの循環検出法でも可能かと思いました)
・無限ループを用いる方法
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
fast = slow = head
while 1:
if fast is None or fast.next is None:
return None
slow = slow.next
fast = fast.next.next
if slow == fast:
return Trueもいかがでしょうか
以下の議論も参考になります
https://discordapp.com/channels/1084280443945353267/1192728121644945439/1194203372115464272
https://discordapp.com/channels/1084280443945353267/1221030192609493053/1225674901445283860
There was a problem hiding this comment.
ありがとうございます。無限ループの書き方もわかりやすいですね。参考になります。
参考議論もありがとうございます!
There was a problem hiding this comment.
if slow == fast:ではなくif slow is fast:とするのには何か理由があるのでしょうか。
There was a problem hiding this comment.
ListNode同士のオブジェクトの比較なので、isにしています。ここは同一のListNodeの比較想定なので、=でも問題ないですね。
There was a problem hiding this comment.
私の間違いだったら申し訳ないのですが,この下にseenにheadが含まれない場合はaddする必要がある気がします.
else:
seen.add(head)There was a problem hiding this comment.
私もadd必要だと思います。
ifの中でreturnしているので、ifの外であればelseはなくてもよさそうです。
There was a problem hiding this comment.
すみません、ご指摘頂きありがとうございます。
コピペの段階で誤って消したみたいです。クリティカルなのでここだけ部分的に修正しました。
There was a problem hiding this comment.
これはおそらくクラスメソッドではなくインスタンスメソッドの話かなと思いました。
(クラスメソッドの最初の引数は一般的にはselfではなくcls)
There was a problem hiding this comment.
ありがとうございます。ご指摘の通りインスタンスメソッドですね。
https://leetcode.com/problems/linked-list-cycle/