1.两数之和
给定一个整数数组
nums
和一个整数目标值target
,请你在该数组中找出 和为目标值target
的那 两个 整数,并返回它们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6 输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6 输出:[0,1]
提示:
2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
- 只会存在一个有效答案
**进阶:**你可以想出一个时间复杂度小于
O(n2)
的算法吗?Related Topics
数组
哈希表
1.时间复杂度O(n2)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
res = []
for i in range(len(nums)):
start, end = nums[i], target - nums[i]
newlist = nums[i + 1:]
if end in newlist:
res.append(i)
res.append(newlist.index(end) + i +1)
return res
循环中都使用了in
操作和index()
函数来在一个子列表newlist
中查找一个元素。这两个操作在Python列表中都需要线性时间复杂度,即O(n),其中n是列表的长度。
2.时间复杂度O(n)
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
num_map = {}
for i, num in enumerate(nums):
complement = target - num
#首先检查 complement 是否在 num_map 中。如果在,就说明找到了一对和为 target 的元素,然后我们记录这对元素的索引。无论 complement 是否在 num_map 中,我们都会将当前的 num 和它的索引 i 添加到 num_map 中。
if complement in num_map:
return [num_map[complement], i]
num_map[num] = i
return []
#Q1
#如果"num_map[num] = i"放在if语句之前,则先将当前的 num 和它的索引 i 添加到 num_map 中,然后检查 complement 是否在 num_map 中。这里有一个潜在的问题,即当 complement 等于 num 时,我们可能会错误地认为找到了一对和为 target 的元素,但实际上我们只是将 num 自己添加到了 num_map 中。
num_map[num] = i
if complement in num_map:
res =[num_map[complement], i]
#例如,考虑 nums = [2, 7, 11, 15] 和 target = 4。当 i = 0(也就是 num = 2)时,complement 就等于 target - num = 4 - 2 = 2。在第二段代码中,我们先将 num 添加到 num_map 中,然后发现 complement 也在 num_map 中,就会错误地认为找到了一对和为 target 的元素,但实际上我们只是将 num 自己添加到了 num_map 中。
使用一个字典num_map
来存储已经遍历过的数字及其索引。然后,对于输入列表中的每一个数字,我们都计算目标和与它的差值,然后在字典中查找这个差值是否存在。如果存在,说明我们已经找到了两个和为目标的数字,所以我们就返回它们的索引。如果不存在,我们就将当前数字及其索引添加到字典中。这样,我们只需要遍历一次输入列表,所以时间复杂度是O(n)。