给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。这题能用哈希表做吗?
时间: 2024-06-16 22:06:22 浏览: 12
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数,并返回它们的数组下标。这题可以使用哈希表来解决。
使用哈希表的思路如下:
1. 创建一个空的哈希表,用于存储数组中的元素和它们的索引。
2. 遍历数组中的每个元素,对于每个元素 nums[i],计算出目标值与当前元素的差值 diff = target - nums[i]。
3. 在哈希表中查找差值 diff,如果存在,则返回差值 diff 对应的索引和当前元素的索引。
4. 如果差值 diff 不存在于哈希表中,则将当前元素及其索引添加到哈希表中。
下面是使用哈希表解决该问题的示例代码:
```python
def twoSum(nums, target):
# 创建一个空的哈希表
hashmap = {}
# 遍历数组中的每个元素
for i in range(len(nums)):
# 计算差值
diff = target - nums[i]
# 在哈希表中查找差值
if diff in hashmap:
# 如果差值存在于哈希表中,则返回差值对应的索引和当前元素的索引
return [hashmap[diff], i]
# 将当前元素及其索引添加到哈希表中
hashmap[nums[i]] = i
# 如果没有找到符合条件的两个元素,则返回空列表
return []
# 示例输入
nums = [2, 7, 11, 15]
target = 9
# 调用函数并输出结果
print(twoSum(nums, target)) # 输出:[0, 1]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)