Linux 拨号vps windows公众号手机端

python两数之和怎么求

lewis 7年前 (2018-03-18) 阅读数 11 #程序编程
文章标签 python

要求两个数的和,可以使用以下代码实现:

def two_sum(nums, target):
    hash_map = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in hash_map:
            return [hash_map[complement], i]
        hash_map[num] = i
    return None

nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
if result:
    print(f"两数的索引为: {result}")
else:
    print("没有找到符合条件的两个数")

在这段代码中,two_sum 函数接受一个包含整数的列表 nums 和一个目标值 target 作为参数。函数通过遍历 nums 列表并将元素的值和索引存储在哈希表 hash_map 中,然后计算每个元素与目标值的差值 complement,检查是否存在该差值在 hash_map 中,如果存在则返回两个数的索引。如果遍历结束后没有找到符合条件的两个数,则返回 None

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门