Create 142. Linked List Cycle II.md#3
Conversation
| while head: | ||
| if head in visited: | ||
| return pos | ||
| pos = pos+1 |
There was a problem hiding this comment.
pos = pos + 1 とスペースを空けたいですね。or pos += 1
| # 別解: fastとslowを用いる解法 | ||
| class Solution: | ||
| def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: | ||
| if head is None: |
There was a problem hiding this comment.
is not None を用いる条件文と、None が falsy であることを利用した暗黙評価の条件文が混在しているようです。どちらかに統一した方がよいと思います。Google Style Guide だと is (not) None 推奨ですね。
https://google.github.io/styleguide/pyguide.html#2144-decision
There was a problem hiding this comment.
while node:
→
while node is not None:
while fast.next and fast.next.next:
→
while fast is not None and fast.next is not None:
ですね。明示がないと誤判定による事故が起きる可能性があるんですね。ありがとうございます!
| return None | ||
|
|
||
| slow = head | ||
| while slow != fast: |
There was a problem hiding this comment.
- != は 値が違うものか判定
- is not はNoneやboolにも対応
という認識なので調べました。
!=の認識は良さそうです。オブジェクト型が違っても良いということに注意。
6.10.1. Value comparisons
The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects do not need to have the same type.
https://docs.python.org/3/reference/expressions.html
is not は「オブジェクトが同一でないかどうか」の判定ですね。is notの働きを聞かれているのに、他のものと合わせる使い方で答えるのはよくないです。もう少し何を比較しているかで、言葉をまとめられると正解でした。また、is notを値の比較と解釈していたら、valだけが重複するものが出た時に訪問済みか判定できないですねと判定してしまいますね
6.10.3. Identity comparisons
The operators is and is not test for an object’s identity: x is y is true if and only if x and y are the same object. An Object’s identity is determined using the id() function. x is not y yields the inverse truth value. [4]
https://docs.python.org/3/reference/expressions.html
諸々ご指摘ありがとうございます。
| 位置 25: 中央値 5667 ns | ||
| 位置 50: 中央値 5583 ns | ||
| 位置 75: 中央値 5750 ns | ||
| 位置 99: 中央値 5709 ns |
There was a problem hiding this comment.
setを使ってもノードを1個1個処理していかなければいけないのでサイクルの位置が後ろにいくほど時間は上がるかなと思ったのですが、そうでもないんですね。勉強になります。
コードは良いと思いました。
|
|
||
| ``` | ||
|
|
||
| スマホで初めてLeetcodeに書いたので手こずった。acceptedだが、141. Linked List Cycleの時に気を付けていたnodeへのhead代入ができていない。焦ると綺麗にするのをまだ忘れる。負け惜しみだが、これは5分を切れた。なんだか勿体無い気がする。 |
There was a problem hiding this comment.
殆どのソフトウェアエンジニアは PC とキーボードでコードを書くと思います。 PC とキーボードで書くことをおすすめします。
ガラケー時代に、ガラケーを使ってオンラインジャッジで問題を解いている人は見かけたことがあります。
There was a problem hiding this comment.
ありがとうございます。
スマホ使用はレビューの時に限定しようと思います。
| 境界 3: 要素数 77 で 2264 → 8408 bytes (+6144 bytes) | ||
|
|
||
|
|
||
| 要素数2^6=64について、 64・3/5=38 近辺でリサイズが起きていないのが不思議だが、(ListNodeの要素数)・107+216 bytes ほどで見積もれそう。 |
There was a problem hiding this comment.
CPythonだと以下の部分ですかね。
if ((size_t)so->fill*5 < mask*3)
return 0;
return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);There was a problem hiding this comment.
ありがとうございます。ref見て気づきました。usedの4倍なので要素数64の時はリサイズないですね。助かりました。
This problem
https://leetcode.com/problems/linked-list-cycle-ii/description/
Next
https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
言語
Python