要求两个数的和,可以使用以下代码实现:
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 Nonenums = [2, 7, 11, 15]target = 9result = two_sum(nums, target)if result: print(f"两数的索引为: {result}")else: print("没有找到符合条件的两个数")在这段代码中,two_sum 函数接受一个包含整数的列表 nums 和一个目标值 target 作为参数。函数通过遍历 nums 列表并将元素的值和索引存储在哈希表 hash_map 中,然后计算每个元素与目标值的差值 complement,检查是否存在该差值在 hash_map 中,如果存在则返回两个数的索引。如果遍历结束后没有找到符合条件的两个数,则返回 None。




