diff --git a/1. Two Sum.md b/1. Two Sum.md new file mode 100644 index 0000000..fb497d3 --- /dev/null +++ b/1. Two Sum.md @@ -0,0 +1,85 @@ +URL: https://leetcode.com/problems/two-sum/ + +# Step 1 + +- 実装時間: 2分 +- 時間計算量: O(n^2) +- 空間計算量: O(1) + +```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: + return [i, j] +``` + +# Step 2 + +- 参考にしたURL + - https://github.com/Yoshiki-Iwasa/Arai60/pull/10 + - https://github.com/aoshi2025s/leetcode-review/pull/1 + - https://github.com/seal-azarashi/leetcode/pull/11 + - https://github.com/hroc135/leetcode/pull/11 + - https://github.com/rihib/leetcode/pull/8 + - https://github.com/ryo-devz/LeetCode/pull/2 + - https://github.com/ryoooooory/LeetCode/pull/18 + - https://github.com/takumihara/leetcode/pull/1 + - https://github.com/tarinaihitori/leetcode/pull/11 + - https://github.com/haniwachann/leetcode/pull/2 + - https://github.com/philip82148/leetcode-arai60/pull/1 + +- c++でcontainsを使って解いているのを見た。 + - https://github.com/aoshi2025s/leetcode-review/pull/1 + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_to_index = {} + for i, num in enumerate(nums): + if num in num_to_index: + return [i, num_to_index[num]] + num_to_index[target - num] = i +``` + +- 不正入力の場合どうするのかは、考えておこう。 + - 例えば、今回の関数がパイプラインやCI/CDなどエラー時すぐに担当者に知らせたいような場合はExceptionを投げて上げたほうがいいかもしれません +Exceptionを発生させないのであれば、nilを返しつつ error logを吐いておくのもありかなと思いました + - https://github.com/rihib/leetcode/pull/8/files#r1706918313 + - returnを書かなければNoneを返す + - https://docs.python.org/3/tutorial/controlflow.html#defining-functions + +- `+`の前後のスペースを入れるべきか。 + - Use your better judgment for the insertion of spaces around arithmetic operators + - https://google.github.io/styleguide/pyguide.html#s3.6-whitespace + - 優先順位の異なる演算子を使用する場合は、優先順位がもっとも低い演算子の周囲に空白を追加することを検討してください。独自の判断で使用してください。ただし、複数のスペースは使用しないでください。また、バイナリ演算子の両側には常に同じ量の空白を入れてください。 + - https://peps.python.org/pep-0008/#other-recommendations + - 考えた結果今回は以下のようなのがいいと思った。 + - `if nums[i]+nums[j] == target:`では`==`がもっとも優先度が低いので、`+`の周りはスペースをあけない。 + +```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: + return [i, j] +``` + +# Step 3 + +- 時間計算量: O(n) +- 空間計算量: O(n) + +```python +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + num_to_index = {} + for i, num in enumerate(nums): + if num in num_to_index: + return [i, num_to_index[num]] + num_to_index[target - num] = i +``` + +最後に気づいたけど、`num_to_index`より`complement_to_index`の方が、より適切な名前かもしれない。