【Python】两数之和:哈希表

导航

自己: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