1. two sum - #1
Conversation
| for j in range(i + 1, len(nums)): | ||
| if nums[i] + nums[j] == target: | ||
| answer = [i, j] | ||
| break |
There was a problem hiding this comment.
ここでbreakをしているのはループを抜ける意図だと思うのですが、この書き方だと内側のfor jだけを抜けて、外側のfor iは継続します。
答えを得た時点で、return [i, j]で即座に返すのが個人的に良いと思います。
| diff = target - nums[i] | ||
| if diff in visited: | ||
| answer = [visited[diff], i] | ||
| break |
| if nums[i] + nums[j] == target: | ||
| answer = [i, j] | ||
| break | ||
| return answer |
There was a problem hiding this comment.
if nums[i] + nums[j] == target:
return [i, j]と書いてもいいと思います。
| else: | ||
| visited[nums[i]] = i | ||
| return answer | ||
|
|
There was a problem hiding this comment.
step1とstep2のどちらのコードも
targetと一致する数のペアがが見つからなかったとき、answerが未定義のままreturnされますね。
| ```python | ||
| class Solution: | ||
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| visited = {} |
There was a problem hiding this comment.
visited という変数名は、グラフの探索等で、探索済み挑戦の集合を格納するために使うことが多いように感じます。また、 dict 型の変数名は、 (キー)_to_(値) という書式で、キーと値にどのようなものが含まれているかを表すのをよく見かけます。 num_to_index はいかがでしょうか?
| class Solution: | ||
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| visited = {} | ||
| for i in range(len(nums)): |
There was a problem hiding this comment.
for i, num in enumerate(nums):と、インデックスと値を同時にとったほうがシンプルになると思います。
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| visited = {} | ||
| for i in range(len(nums)): | ||
| diff = target - nums[i] |
There was a problem hiding this comment.
complement という変数名を使っている方も見かけました。趣味の範囲だと思います。
| break | ||
| else: | ||
| visited[nums[i]] = i | ||
| return answer |
There was a problem hiding this comment.
answerという変数名はleetcodeに寄りすぎていて、現実で使われるコードではそれほど好まれないようです。
https://discord.com/channels/1084280443945353267/1358954923672207420/1462241459209240751
https://docs.google.com/document/u/1/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/mobilebasic#h.fcs3httrll4l
No description provided.