leecode 两数之和的四种解法:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
解法1:
class Solution:
def twoSum( sself,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i=0
j=1
for num1 in nums:
i=i+1
j=i
for num2 in nums[j:]:
j=j+1
if num1+num2==target:
return [i-1,j-1]
这种方法最容易想到,两个for循环就可及解决,但是时间复杂度太高,leecode没给过
解法2:
class Solution:
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
j=-1
lens=len(nums)
print(range(lens))
for n1 in range(lens):
t=nums[:n1]
if target-nums[n1] in t:
j=t.index(target-nums[n1])
break
return [j,n1]
但是时间长,内存占用多
解法3:
这里利用了字典来查找,速度提升很大,与哈希表的原理有关
class Solution:
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict1 = {}
for i, num in enumerate(nums):
dict1[num] = i # 调换一个顺序
for i, num in enumerate(nums):
j=dict1.get(target-num)
if j!=None and i!=j :
return [i,j]
关于enumerate函数
效果如下:
解法4:
class Solution:
def twoSum(self,nums,target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dict1 = {}
for i, num in enumerate(nums):
j=dict1.get(target-num)
if j!=None and j!=i:
return[j,i]
dict1[num] = i # 调换一个顺序。在后面防止字典键值有重复
这个就只用到了一个循环
但效果、、、