Conversation
| - ソートする方とはなんだろう? | ||
| - ソートして、先頭と末尾の和から見ていって↓を繰り返すとか? | ||
| - 和が target より大きいなら、後ろのポインタを一つ前に | ||
| - 〃小さいなら、前のポインタを一つ後ろに |
There was a problem hiding this comment.
他の人のコードも見つけてきましたが,言及されている通りのようですね
https://github.com/fuga-98/arai60/pull/12/changes#diff-e05ee5891f6b31ddafd0fa4d5497330fedc2954d82a170f4b6fc95f8f48d4d2cR41-R64
There was a problem hiding this comment.
ありがとうございます、そのようですね。
この方のコードで、辞書に詰めなくて「set で存在確認→ list.index() で index を取得」というのもなるほどと思いました。
| class Solution: | ||
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| num_to_index = {} | ||
| for index, num in enumerate(nums): | ||
| pair_index = num_to_index.get(target - num) | ||
| if pair_index is None: | ||
| num_to_index[num] = index | ||
| continue | ||
| return [index, pair_index] |
There was a problem hiding this comment.
自分のコードは2回ループしてたので,違う書き方で参考になりました.
miyataka/coding-practice#11
同一indexでないというチェックがないのはなぜだろう,というようなことを考えてたりしましたが,1回ループverだと不要になるんですね.
There was a problem hiding this comment.
私も最初はそうしてたのですが、 huyfififi/coding-challenges#1 を見てなるほどと思い、真似してみました
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| num_to_index = {} | ||
| for index, num in enumerate(nums): | ||
| pair_index = num_to_index.get(target - num) |
There was a problem hiding this comment.
ありがとうございます。補数ということですね。より実態を表した名前だと思います。
|
|
||
| class Solution: | ||
| def twoSum(self, nums: List[int], target: int) -> List[int]: | ||
| num_to_indices: Dict[int, List[int]] = {} |
There was a problem hiding this comment.
Python 3.9 以降では dict[int, list[int]] と書けるようです。
There was a problem hiding this comment.
ありがとうございます。そのようですね。↓のコメントでも言及されていますね。
この問題:https://leetcode.com/problems/two-sum/
次の問題:https://leetcode.com/problems/group-anagrams/