Conversation
1.Two Sum/memo.md
Outdated
| 空間 | ||
| O(n^2) | ||
|
|
||
| 問題のジャンルがhash mapなのでmapを使った解法を考える |
There was a problem hiding this comment.
There was a problem hiding this comment.
@liquo-rice 指摘ありがとうございます。きちんと調べると計算量など違うのですね。
memo.mdも修正しました。
mapのcontainsを使う場合(log n)なので合計O(n log n)
https://en.cppreference.com/w/cpp/container/map/contains
unordered_mapのcontainsを使う場合はO(n)なので合計O(n^2)
https://en.cppreference.com/w/cpp/container/unordered_map/contains
| class Solution { | ||
| public: | ||
| vector<int> twoSum(vector<int>& numbers, int target) { | ||
| map<int, int> numbers_to_index; |
There was a problem hiding this comment.
細かいですが、numbersは複数形でindexは単数形なのが気になりましたmm
個人的にはmapの一つのエントリを指す名前の方が直感的なので単数形でnum_to_indexとかが良さそうかなと思いましたmm
There was a problem hiding this comment.
@erutako
step5に追加しました。統一感の意識はしておかないとですね。。。
reflecting review
| for (int j = 0; j < numbers.size(); j++) { | ||
| if (i != j && target - numbers[i] - numbers[j] == 0) { |
There was a problem hiding this comment.
loopで書くなら、内側のfor文のカウント変数の初期化を int j = i + 1のようにして、全探索にしても余分な計算は省くとよいのかなと思いましたmm
これをすればif文の条件で i != jがいらなくなるので、そこも読みやすくなってメリットがあるかなと思います。
There was a problem hiding this comment.
@erutako
ありがとうございます!確かに初めからループさせる必要ないですね。。。
loop2.cppにて実装しました🙇
reflecting review
1.Two Sum/memo.md
Outdated
| 時間 | ||
| O(n^2) | ||
| 空間 | ||
| O(n^2) |
There was a problem hiding this comment.
アルゴリズムにおいて追加で必要な空間という意味ではi, j, two_indicesぐらいなのでO(1)ではないでしょうか?
numbersの空間を計算量に入れたとしても、O(N)な気がします。
There was a problem hiding this comment.
@erutako レビューありがとうございます。誤っておりました。ご指摘のとおり、それぞれO(1)ですね。。。
reflecting reviewにて修正しました。
|
メモ |
| vector<int> twoSum(vector<int>& numbers, int target) { | ||
|
|
||
| vector<int> two_indices; | ||
| for (int i = 0; i < numbers.size(); i++) { |
There was a problem hiding this comment.
結果は同じですが、i < numbers.size() - 1とした方が良さそうです。
There was a problem hiding this comment.
j = i + 1とするならこちらの方がいいですね。ループの回数もきちんと意識します。
| vector<int> two_indices; | ||
| for (int i = 0; i < numbers.size(); i++) { | ||
| for (int j = i + 1; j < numbers.size(); j++) { | ||
| if (target - numbers[i] - numbers[j] == 0) { |
There was a problem hiding this comment.
普通はnumbers[i] + numbers[j] == targetとしませんか?
There was a problem hiding this comment.
@liquo-rice そうですね。他の解法で使ったremainingにつられてました。。。
| if (target - numbers[i] - numbers[j] == 0) { | ||
| two_indices.push_back(i); | ||
| two_indices.push_back(j); | ||
| return two_indices; |
There was a problem hiding this comment.
@liquo-rice
わざわざ変数に入れる必要ないですね。
下記にてloop3.cppを追加しました。
3bd35d9
問題へのリンク
https://leetcode.com/problems/two-sum/description/
問題文(プレミアムの場合)
備考
次に解く問題の予告
Group Anagrams
フォルダ構成
LeetCodeの問題ごとにフォルダを作成します。
フォルダ内は、step1.cpp、step2.cpp、step3.cpp、loop.cppとmemo.mdとなります。
memo.md内に各ステップで感じたことを追記します。