题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
这里我们提供两种解决方案与在本地工具上实现结果
方案一(使用列表,循环判断,比较耗时):
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
x = len(nums) #获取列表长度,准备循环计算
for i in range(x):
j = target-nums[i]
if j in nums:
x = nums.index(j)
if x != i:
return i,x
方案二(参考用字典大大降低时间复杂度):
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dict={
} #定义一个字典
for i,element in enumerate(nums):
if target-element in dict:
return [dict[target-element],i]
dict[element] = i
将leetcode的题在本地运行需要注意调整函数后传参数(如图所示)