两数之和
给定一个整数数组 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]:
for i in range(len(nums)-1):
for j in range(i+1, len(nums)):
if nums[i]+nums[j] == target:
return [i, j]
执行结果:通过
显示详情
执行用时 :6904 ms, 在所有 Python3 提交中击败了5.00%的用户
内存消耗 :14 MB, 在所有 Python3 提交中击败了71.71%的用户
时间复杂度为O(n^2)
换用字典
在第一次遍历的过程中我们把数据按字典的方式存下来,下一个遍历过程中直接用差值(目标-当前遍历的值)去字典中查询,如果有结果则直接返回结果。
class Solution:
def twoSum``(self, nums: List[int], target: int) -> List[int]:
l=len(nums)
zidian={}
for i in range(l):
j=target-nums[i]
if j in zidian:
return [zidian[j],i]
zidian[nums[i]]=i