题目
1. 两数之和 - 力扣(LeetCode)
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 _ target
_ 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
思路
- 暴力解法:两层 for 循环,时间复杂度 O (n^2)
- 为省时间,争取用一层循环完成
- 因为要查找 和为目标值的数,因此查询的是数组元素,但返回的却是数组下标,故需要用哈希表记录元素和其下标
- 对每一个元素 value ,若哈希表中有 对应
target-value
,则配对成功。否则将此元素加入哈希表,等待后续元素配对。
要点
- 编程基础:
enumerate()
函数用于给可迭代对象生成索引和值的配对
nums = [10, 20, 30]
for index, value in enumerate(nums):
print(f"索引: {index}, 值: {value}")
# 输出:
# 索引: 0, 值: 10
# 索引: 1, 值: 20
# 索引: 2, 值: 30
代码
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
records = dict()
for index, value in enumerate(nums):
if target - value in records: # 遍历当前元素,并在map中寻找是否有匹配的key
return [records[target- value], index]
records[value] = index # 如果没找到匹配对,就把访问过的元素和下标加入到map中
return []