给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
PS:Python index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。
index()方法语法: str.index(str, beg=0, end=len(string))
1.可以对数组中的每一个元素进行遍历,用目标值减去遍历的元素值,得出的值与数组中的数进行比较。
class Solution( ):
def twoSum(self, nums, target):
\"\"\"
:type nums: List[int]
:type target: int
:rtype: List[int]
\"\"\"
for i in range(len(nums)):
x = target - nums[i]
if x in nums:
j = nums.index(x)
if j != i:
return i,j
时间复杂度:O(n2),空间复杂度:O(1) ( 因为python中list对象的存储结构采用的是线性表,因此其查询复杂度为O(n)。
那么if x in nums的时间复杂度就是O(n) )
2.暴力解法,遍历列表中的每一个值,然后再遍历不包括上一个值的每一个值,如果这两个值的和为目标值,返回。
class Solution( ):
def twoSum(self, nums, target):
\"\"\"
:type nums: List[int]
:type target: int
:rtype: List[int]
\"\"\"
n = len(nums)
for x in range(n):
for y in range(x+1,n):
if nums[y] == target - nums[x]:
return x,y
时间复杂度:O(n2)、空间复杂度:O(1)
3.还有一种字典的方法,时间复杂度:O(1) 、空间复杂度O(n) (python中dict对象的存储结构采用的是散列表(hash表),其在最优情况下查询复杂度为O(1))
class Solution:
def twoSum(self, nums, target):
\"\"\"
:type nums: List[int]
:type target: int
:rtype: List[int]
\"\"\"
n = len(nums)
d = {}
for x in range(n):
a = target - nums[x]
#字典d中存在nums[x]时
if nums[x] in d:
return d[nums[x]],x
#否则往字典增加键/值对
else:
d[a] = x
#边往字典增加键/值对,边与nums[x]进行对比
继续阅读与本文标签相同的文章
-
打通“最后一公里”送药地图 访海派医药集团总经理张翔
2026-05-18栏目: 教程
-
上海首个保税展示展销场所亮相 海外商品“全球同质同价”
2026-05-18栏目: 教程
-
微信聊天记录导出excel使用方法分享卓师兄微信恢复大师
2026-05-18栏目: 教程
-
用好SmartArt,快速制作美观工整的PPT
2026-05-18栏目: 教程
-
CMU 15-721 15-查询执行和处理过程 Query Execution & Processing
2026-05-18栏目: 教程
