Open
Conversation
Ryotaro25
reviewed
Jun 10, 2024
| int carry = 0; | ||
| ListNode dummy_head; | ||
| ListNode* node = &dummy_head; | ||
| while (list2 || list1) { |
There was a problem hiding this comment.
while (list1 || list2)の方が違和感ないと思いました🙇
Owner
Author
There was a problem hiding this comment.
気付きませんでした。ご指摘ありがとうございます。
Ryotaro25
reviewed
Jun 10, 2024
| - time: O(n), space: O(n) | ||
| - 繰り上がりが最後に残った場合のみ注意 | ||
| - リストの走査は繰り返しでも再帰でもOK | ||
| - 再帰にするメリットは思いつかないので繰り返しでいく |
There was a problem hiding this comment.
再帰に関しても時間/空間計算量やコードに落とす際の観点も踏まえた方が
なぜ @kazukiii さんが今回の実装を選ばれたのかがより伝わると思いました。
よく自分が受けている指摘ですが🙇
Owner
Author
There was a problem hiding this comment.
レビューありがとうございます。なぜ選択したのかも言語化して残すようにしてみます。
以下、今回の問題に関して考えることです。
再帰に関しては実装方法の違いだと考えており、時間/空間計算量は同じになります。
再帰処理に関しては、再帰的な関数呼び出しや呼び出しごとに生成されるスタックフレームを考えると、時間的にも空間的にもオーバーヘッドが多少あるため、今回繰り返しを選択しました。
一応再帰でも書いてみました->c9ba9b4
liquo-rice
reviewed
Jun 10, 2024
| - 新しいノードをスタック領域に確保するとスコープを抜けた時点でメモリが解放されるのでうまくいかない | ||
| - ヒープ領域にオブジェクトを作成したけど、このオブジェクトの管理は誰の責務になるのかがわかっていない | ||
| - C++実務で使ったことないが、実務だとどうやるんだろう | ||
| - Linked Listのポインタをスマートポインタにすればよさそう? -> 参照が切れた時点で自動的にメモリが解放されそう |
There was a problem hiding this comment.
Owner
Author
There was a problem hiding this comment.
ありがとうございます。理解が深まりました。
- 動的に確保されたオブジェクトには所有者を設定する
- その所有者がオブジェクトのメモリ管理に関する責任を持つ
- 基本的には、所有権はuniqueにする(std::unique_ptrを使う)
- 以上を元に実務では以下のようにすればいいと考えました
- Linked Listのポインタをstd::unique_ptrで定義する
- std::make_uniqueでスマートポインタを生成
- Linked Listに追加する際に、所有権をmoveする
oda
reviewed
Jun 10, 2024
| class Solution { | ||
| public: | ||
| ListNode* addTwoNumbers(ListNode* list1, ListNode* list2) { | ||
| ListNode dummy_head; |
|
いいとおもいます! |
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.
問題へのリンク
https://leetcode.com/problems/add-two-numbers/description/
次に解く問題
20. Valid Parentheses
README.mdへ頭の中の言語化と記録をしています。