Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions 1. Two Sum/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
問題は1. Two Sum(https://leetcode.com/problems/two-sum/description/?envType=problem-list-v2&envId=xo2bgr0r)

次に解くのは387. First Unique Character in a String(https://leetcode.com/problems/first-unique-character-in-a-string/?envType=problem-list-v2&envId=xo2bgr0r)

## Step 1
先頭から順番に各要素について後ろにある各要素を足してtargetと比較するやり方が一番直感的に思いついたので書いてみる。各要素について線形の走査が入るので時間計算量がO(n^2)になる。想定解法ではないが一回書いてみる。
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
answer = [i, j]
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここでbreakをしているのはループを抜ける意図だと思うのですが、この書き方だと内側のfor jだけを抜けて、外側のfor iは継続します。
答えを得た時点で、return [i, j]で即座に返すのが個人的に良いと思います。

return answer

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

               if nums[i] + nums[j] == target:
                    return [i, j]

と書いてもいいと思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!納得しました。

```
## Step 2
先頭の要素から順番に、targetとの差分を計算して、その差分の値がそれより前にあればそのindexを持ってくるやり方であれば、1回の走査とハッシュマップへのアクセスだけで済むので、時間計算量はO(n)になる。一方でハッシュマップを置いておくメモリが必要で、そのメモリはnumsの要素数に対して比例になるため、空間計算量もO(n)になる。
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
visited = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

visited という変数名は、グラフの探索等で、探索済み挑戦の集合を格納するために使うことが多いように感じます。また、 dict 型の変数名は、 (キー)_to_(値) という書式で、キーと値にどのようなものが含まれているかを表すのをよく見かけます。 num_to_index はいかがでしょうか?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!納得しました。

for i in range(len(nums)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

for i, num in enumerate(nums):

と、インデックスと値を同時にとったほうがシンプルになると思います。

diff = target - nums[i]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

complement という変数名を使っている方も見かけました。趣味の範囲だと思います。

if diff in visited:
answer = [visited[diff], i]
break

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ここについても、答えを得たらすぐにreturnして良いと思います。

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!納得しました。

else:
visited[nums[i]] = i
return answer

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

answerという変数名はleetcodeに寄りすぎていて、現実で使われるコードではそれほど好まれないようです。
https://discord.com/channels/1084280443945353267/1358954923672207420/1462241459209240751
https://docs.google.com/document/u/1/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/mobilebasic#h.fcs3httrll4l

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

ありがとうございます!納得しました。


@h-masder h-masder Apr 4, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

step1とstep2のどちらのコードも
targetと一致する数のペアがが見つからなかったとき、answerが未定義のままreturnされますね。

```

## Step3
これまでもらった指摘を基に書き直してみる。
```Python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_to_index = {}
for i, num in enumerate(nums):
complement = target - num
if complement in num_to_index:
return [num_to_index[complement], i]
else:
num_to_index[num] = i

```