力扣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)
的算法吗?
这个题主要有两个点需要注意:1.list中有重复值。2.target-num=num
第一次 写出来是这样的,并且没有加nums.index(target-i)!=index的判断条件。
数组索引和值同时遍历:for index,i in enumerate(list)
数组根据值获取索引:list.index(值)
763ms,12.62mb。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for index,i in enumerate(nums):
if target-i in nums and nums.index(target-i)!=index:
return index,nums.index(target-i)
第二次看了答案,学会了这种写法,这种写法通过哈希表的方式,将时间复杂度从暴力解法的 O(n²) 优化到 O(n),只需要一次遍历即可找到满足条件的两个数字的索引。
字典返回指定键的值:dict.get(key)
40ms,15.75mb
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap={} # 创建一个空字典 hashmap,用于存储数组中每个数字的索引。键是数组中的数字,值是该数字在数组中的索引。
for index,num in enumerate(nums):
if hashmap.get(target-num) is not None:
return [index,hashmap.get(target-num)]
hashmap[num] = i #这句不能放在if语句之前,解决list中有重复值或target-num=num的情况
问:是什么原因导致了这两种算法的快慢?
答:我用「获取了多少信息」来解释。
暴力做法每次拿两个数出来相加,和 target 比较,那么花费 O(1) 的时间,只获取了 O(1) 的信息。
而哈希表做法,每次查询都能知道 O(n) 个数中是否有 target−nums[j],那么花费 O(1) 的时间,就获取了 O(n) 的信息。
这就是为什么我们可以把暴力的 O(n 2) 优化成 O(n)。
相比暴力做法,哈希表多消耗了内存空间,但减少了运行时间,这就是「空间换时间」。