Skip to content

Conversation

@docto-rin
Copy link
Owner

- これは良さそう。O(n)の定数倍の最適化になる。
- ところで、sequence.reverse()について調べていたところ、以下のように書いてあり興味深かったです。
- > Reverse the items of sequence in place. This method maintains economy of space when reversing a large sequence. **To remind users that it operates by side-effect, it returns None.**
- https://docs.python.org/ja/3.13/library/stdtypes.html#sequence.reverse
Copy link

Choose a reason for hiding this comment

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

sequence.reverse() の他に、built-in の reversed というのもありますね。
https://docs.python.org/3/library/functions.html#reversed

## Step 2

- レビュー by GPT-5
- > 反転自体は問題ありませんが、反転を避けたい場合は「収集中に `appendleft` を使う」手があります。具体的には偶数レベルでは `appendleft(node.val)`、奇数レベルでは `append(node.val)` として `deque` に詰め、最後に `list(...)` 化します。これは「コピー+反転」を避けられます。
Copy link

Choose a reason for hiding this comment

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

list にしているので結果的にコピーされていますよね……。
私は直感的にはこちらのほうが遅い気がします。(どうせそんなに問題になるレベルではないですが。)

- https://github.com/garunitule/coding_practice/pull/27
- > 当時はどちらかというとreverseするための計算量O(N)を節約できるからdequeよさそう、と思っていたのですが、今改めて考えると、おっしゃる通り結局listに変換する際にコピーをするのでその分結局O(N)発生してしまっていて、あまりdequeにすることの旨みはなかったかもしれません。。
- よく考えてみると、reverseの有無によらずlist()でO(N)の計算が入るので、逆に遅くなるまでありそう。
- 例えばリストで頑張るなら、最初にそのレベルの全ノードのプレイスホルダーを作っておいて、zigzagする場合は後ろからインデックスアクセスで詰めていけば若干速いかもしれない。
Copy link

Choose a reason for hiding this comment

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

Python の高速化はあまりというところがあります。
Python を使っている時点で C などから50-100倍くらい遅いので、ネイティブコードで書かれた関数をどう呼ぶかという勝負になってきます。numpy など。
本当に速度が必要だと C を使って拡張モジュールを作ることもできます。
https://docs.python.org/3/extending/extending.html

if is_left_to_right:
index = i
else:
index = len(level_nodes) - 1 - i
Copy link

Choose a reason for hiding this comment

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

Python はマイナスで後ろからアクセスしてくれるので、-1 - i でいいですかね?

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.

3 participants