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
93 changes: 93 additions & 0 deletions 1. Two Sum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
https://leetcode.com/problems/two-sum/

### Description

Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_.

You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice.

You can return the answer in any order.

**Example 1:**

**Input:** nums = [2,7,11,15], target = 9
**Output:** [0,1]
**Explanation:** Because nums[0] + nums[1] == 9, we return [0, 1].

**Example 2:**

**Input:** nums = [3,2,4], target = 6
**Output:** [1,2]

**Example 3:**

**Input:** nums = [3,3], target = 6
**Output:** [0,1]

**Constraints:**

- `2 <= nums.length <= 104`
- `-109 <= nums[i] <= 109`
- `-109 <= target <= 109`
- **Only one valid answer exists.**

**Follow-up:** Can you come up with an algorithm that is less than `O(n2)` time complexity?
### STEP1
brute forceしか思いつかなかったので解答をみた。
nをnumsの長さとして
Time ComplexityO(n) Space ComplexityO(n)
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d = {}
for i, x in enumerate(nums):
d[x] = i
for i, x in enumerate(nums):
if target - x in d and i != d[target - x]:
return [i,d[target-x]]
```

### STEP2
あまりに辞書の変数が酷いけどどうしたもんかなと思っていたら
https://github.com/ksaito0629/leetcode_arai60/pull/10/changes/bb1ae591a98e7810711de49f212bb97f5fc34ce9#r2811748134
辞書の名前としてkey_to_valueはなるほど感がある。
というか2周ループを回す必要は別になくて探しながら追加したらいいだけだな。
あとleetcodeで書くときにエラーをraiseする習慣はなかったけど他の人のコードを見ていると書いているっぽい。仕事なら書いてるけども。

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 するなあなどのコメントが自然に出てくるならばあまり問題は感じないです。

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.

なるほど、ただ習慣として意識せずに書ける方がミスが減るので気をつけます。


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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

二項演算子の両側にスペースが開いているものとあいてないものが混在しており、読み手にとってノイズになりそうだと思いました。

個人的には、二項演算子の左右にスペースを入れることが多いです。

参考までに、関連するスタイルガイドを共有いたします。

https://peps.python.org/pep-0008/#other-recommendations

Always surround these binary operators with a single space on either side: assignment (=), augmented assignment (+=, -= etc.), comparisons (==, <, >, !=, <=, >=, in, not in, is, is not), Booleans (and, or, not).

https://google.github.io/styleguide/pyguide.html#36-whitespace

Surround binary operators with a single space on either side for assignment (=), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Booleans (and, or, not). Use your better judgment for the insertion of spaces around arithmetic operators (+, -, *, /, //, %, **, @).

なお、これらのスタイルガイドは唯一絶対のルールではなく、数あるガイドラインの一つに過ぎません。チームによって重視する書き方が異なる場合もあります。
そのため、ご自身の中に基準を持ちつつも、最終的にはチーム内で一般的とされる書き方に寄せていくことをお勧めいたします。

num_to_index[num] = index
raise NoValueError("There is no such pair that sums to the target")
```
brute forceも一応書いておく。
Time ComplexityO(n^2) Space ComplexityO(1)
```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
length = len(nums)
for i in range(length):
for j in range(i+1, length):
if nums[i] + nums[j] == target:
return [i,j]
raise NoValueError("There is no such pair that sums to the target.")
```

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

target - num は複数回登場する意味のある値なので complementなどと名前をつけるのもアリかもしれません。

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回ぐらいだからいいやと思ってましたが2回目が出てきた瞬間に置き換えてしまった方が良さそうですね。

return [index, num_to_index[target-num]]
num_to_index[num] = index
raise NoValueError("There is no such pair that sums to the target")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

NoValueErrorは組み込み例外ではないので、ここまで到達した場合、NameErrorが出るかと思います。
https://docs.python.org/3/library/exceptions.html#exception-hierarchy

```

そういえばpythonのエラーってどんな感じだったっけと思って見直した

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

こういうのを時々見るのはとてもいい習慣なので続けてください。

https://docs.python.org/3.15/tutorial/errors.html