[Python] 2つの数値の合計:ハッシュテーブル

ナビゲーション

所有:https://sleepymonster.cn/
倉庫:https://github.com/hengyi666

コード:

class Solution:
    def towSum(self, nums: list[int], target: int) -> list[int]:
        dictionary = {
    
    }  # 字典
        for index, num in enumerate(nums):
            if target - num not in dictionary:
                dictionary[num] = index  # 创造 数-下标 键值对
            else:
                return [dictionary[target - num], index]  # 题目确定只有一个答案


nums = [2, 7, 11, 15]
target = 9
print(Solution().towSum(nums, target))

ビープ

一緒に進歩してください、それが助けになるなら、QAQのようにしてください

おすすめ

転載: blog.csdn.net/weixin_51485807/article/details/115310864