leetcode之哈希表与逆向思维的结合
在刷leetcode的时候碰到一道题,内容如下所示:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
我的思路有两种(python版本):
- 暴力破解 ,通过两层循环
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
num_size = len(nums)
"""
res=[]
for ix_left in range(num_size ):
for ix_right in range(ix_left+1 ,num_size):
if target == (nums[ix_left]+ nums[ix_right]):
res.append( [ix_left,ix_right])
if len(res)==1:
res=res[0]
return res
这种思路一般都能想到,但效率比较低,时间复杂度为O(n^2)
2. 逆向思维,利用字典
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic={}
res=[]
for i,num in enumerate(nums):
diff=target-num
if diff in dic:
res.append([dic[diff],i])
dic[num]=i
if len(res)==1:
res=res[0]
return res
题目说的是和为target,可以反过来思考:
对nums遍历,看target和num的差是否在字典的key中,在的话返回key的value(即在num中的index)
这样时间成本上就节约了很多
由于个人水平有限,可能还有考虑不足的地方,欢迎指正