Skip to content
Open
Show file tree
Hide file tree
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
49 changes: 49 additions & 0 deletions 0001-two-sum/memo.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 1. Two Sum

## Step 1
- 二重ループじゃ良くないなと思いつつ総当たりしか思いつきませんでした。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

まあ、見積もって動く場合にはそれでもいいんですが、私の疑問は、仮に数字の書かれた紙が1000枚与えられて、和がいくつになる組みを見つけてくれといわれたら、100万回足し算をしますかということです。

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.

具体的な見積もりも手作業からの類推も、癖付けていきたいと思います。

- 計算量はO(n^2)。

```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i = 0
while i < len(nums) - 1:
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
return [i, j]
j += 1
i += 1

return []
```

## Step 2
- dictに今まで見た数とそのインデックスを登録しながら、新しい数に対して
欲しい差分がdictにないかチェックしていく。
- 線形探索で舐めていき、差分の確認はハッシュマップの確認で基本O(1)なので
トータルはO(n)。
- チェイン法のハッシュマップはハッシュ値 mod 配列長が等しいと
そこでリストを作る(アルゴリズム図鑑)のでO(1)とは限らないらしい。
そのうちPythonの辞書の実装を見てみたい。
- enumurate()を初めて知る。

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

pythonの経験の程度がわからないので,念のためコメントしておきますが,pythonのドキュメントでいうとこことかはざっとみてみるのはいいかもしれません.
https://docs.python.org/3/library/functions.html

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.

まだ2ヶ月くらいのぺーぺーですのでこのあたりも知らないものがありました、共有ありがとうございます。

- エラーケースに自分は空リストを返していたが、先達にあった
raise ValueErrorのほうがベターだと思い変更。
Comment on lines +31 to +32

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

ベターと思ったのはどういう理由からでしょうか?raise するにしても Exception など選択肢がいくつかあるとも思います。
ちなみに私もValueError を返すのが好みです。入力値がおかしいことを端的に示すことができる感じがするためです。

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.

空リストよりraiseのほうが明示的にエラーを示せる、Exceptionは拾う範囲が大きいし(今回はないですが)エラーごとの処理を分けたいときに不便だからといったところです。ValueErrorを選んだ理由は同様です!


```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_to_index = {}
for i, num in enumerate(nums):
diff = target - num
if diff in num_to_index:
return [num_to_index[diff], i]
num_to_index[num] = i

raise ValueError("can't find the solution")
```

## Step 3
- Step 2のコードを三回再現。
- num_to_indexがnum_to_idxになったくらいだった。
27 changes: 27 additions & 0 deletions 0001-two-sum/step1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from typing import List


class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
i = 0
while i < len(nums) - 1:
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
return [i, j]
j += 1
i += 1

return []


def main() -> None:
nums = [3, 2, 4]
target = 6
Solver = Solution()
res = Solver.twoSum(nums, target)
print(res)


if __name__ == "__main__":
main()
10 changes: 10 additions & 0 deletions 0001-two-sum/step2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
num_to_index: dict[int, int] = {}
for i, num in enumerate(nums):
diff = target - num
if diff in num_to_index:
return [num_to_index[diff], i]
Comment on lines +6 to +7

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 で答えを返すよりも、条件を反転させて continue する方が好みです。早期 return で答えを返すようにしていると、あとから別の早期 return を追加していった場合にどれが答えを返しているのかの視認性が悪くなるのではと思うためです。
https://discord.com/channels/1084280443945353267/1201211204547383386/1207251531041210408

if not diff in num_to_index:
  num_to_index[num] = i
  continue

@tsadamor tsadamor Jul 18, 2026

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.

参照先の、

if の中のほうが、普通ではない、異常な、変わったことが起きて欲しいという感覚

これは同じ感覚なのでcontinue派になります。

早期 return で答えを返すようにしていると、あとから別の早期 return を追加していった場合にどれが答えを返しているのかの視認性が悪くなる

あまり出会ったことがないのですが仰っていることはわかりますので、頭に留めておきます。

num_to_index[num] = i

raise ValueError("can't find the solution")