leetcode刷题笔记-两数相加-1
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解题思路:
从最简单的遍历两次数组nums实现目的,但这样输出结果尽管正确,计算时间却溢出了,因此需要优化。
我的解决方法是:仅遍历一次全数组,第二次遍历的时候,直接省去已经遍历过的数组元素。虽然结果最终通过了,但是算法的复杂度仍然为o(n^2)。很捞
class Solution(object):
def twoSum(self, nums, target):
len_nums = len(nums)
for index_1 in range(len(nums)):
for index_2 in range(index_1+1,len_nums):
if(nums[index_1] + nums[index_2] == target):
return index_1,index_2
看了讨论区发现了一种复杂度仅为o(n)的方法。很高级,记下来。
若将数组中和满足条件的两个元素看作“匹配”,则这种方法利用了字典来存储“未匹配的单个元素的值与索引”,enumerate能返回list中元素的值及其索引,仅仅需要遍历一遍数组nums,就可以找出符合条件的两个值。
class Solution:
def twoSum(self, nums, target):
hashmap = {}
for index, num in enumerate(nums):
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index
return None