Skip to content

1. Two Sum#12

Open
X-XsleepZzz wants to merge 5 commits intomainfrom
X-XsleepZzz-patch-1
Open

1. Two Sum#12
X-XsleepZzz wants to merge 5 commits intomainfrom
X-XsleepZzz-patch-1

Conversation

@X-XsleepZzz
Copy link
Copy Markdown
Owner

問題文
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.

url: 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.
Refactor twoSum function to use a hash map for O(n) time complexity. Update error handling and variable naming for clarity.
Added analysis of time and space complexity for the Two Sum problem. Discussed the inefficiency of O(n^2) solutions and considerations for using itertools.
Updated explanations and code comments for the Two Sum problem, clarifying time and space complexity analysis.
Update space complexity analysis for itertools.combinations usage.
時間計算量これならO(n)だし、num_to_indexに追加していくので最悪空間計算量O(n)
Hashのカテゴリに入っていたし辞書使いそうなのは思いついたが、target - numで一致するものを探すというのは思いつかなかった。
コメントで指摘されていたようにcomplementつけたほうがわかりやすそう。
ValueErrorが標準なので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.

https://docs.python.org/3/library/exceptions.html
エラーはこれですね。

itertools を docs で調べているの、とてもよい欲求と思います。

for i in range(len(nums)):
for j in range(i + 1 , len(nums)):
if nums[i] + nums[j] == target:
result_list.extend([i, j])
Copy link
Copy Markdown

@kitano-kazuki kitano-kazuki Mar 1, 2026

Choose a reason for hiding this comment

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

extendよりappendの方が自然だと思いました. (あるいはextendを使いたい場合は, result_listではなく, index_pairのように変数名を変更した方が適切だと感じました)

extendappendを複数回するような動作です
https://docs.python.org/3/tutorial/datastructures.html#:~:text=list.extend(iterable)

Extend the list by appending all the items from the iterable

result_listresultとなる候補を入れるリストだとよめて, この書き方はiという結果とjという結果をそれぞれappendしているような感覚です.

上記は全て解が複数個想定される問題設定だったときの話です

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度手間になるのでextendである必要ないですねmm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants