让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
根据提供的图片内容,问题大致为如下:
**问题描述:** 给定一个整数数组和一个目标值,求出数组中任意两个元素的和等于目标值的两个索引。
**要求:**
- 返回的结果索引从0开始计数。
- 每个输入只对应一个答案,不能使用同一个元素两次。
- 时间复杂度最好为O(n)。 示例: 输入:
nums = [2, 7, 11, 15], target = 9
输出:[0, 1]
解释:nums[0] + nums[1] = 2 + 7 = 9
,返回结果为 [0, 1]
。 代码示例:
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
# 示例输入
nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print(result) # Output: [0, 1]