目录
0001.两数之和
题目:
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和
为目标值 target
的那 两个 整数,并返回它们的数组下标。
思路1:
直接用两层循环暴力求解,算法复杂度为
O
(
n
2
)
O(n^2)
O(n2)。
第一层循环遍历数组中的所有元素,第二层循环找数组织该元素之后的元素是否等于
t
a
r
g
e
t
−
n
u
m
s
[
i
]
target-nums[i]
target−nums[i]即可。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
lens = len(nums)
find_tage = False
result = [0,0]
for i in range(lens-1):
cur = nums[i]
for j in range(i+1,lens):
if nums[j] == target - cur:
find_tage = True
result[1] = j
break
if find_tage:
result[0] = i
break
return result
思路2:
如果想要摆脱双层循环,实现低于
O
(
n
2
)
O(n^2)
O(n2)的算法复杂度,可以考虑使用字典的键值对进行求解。只使用一层循环,每次将
t
a
r
g
e
t
−
n
u
m
s
[
i
]
target-nums[i]
target−nums[i]作为键在字典中查找,找到则返回结果;未找到则将
n
u
m
s
[
i
]
nums[i]
nums[i]存入字典中。
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
numDict = dict()
for i in range(len(nums)):
if (target - nums[i]) in numDict:
return numDict[target - nums[i]],i
numDict[nums[i]] = i
优化效果十分明显: