"""复杂度O(n)"""
class Solution:
def twoSum(self, nums, target):
dict1={}
for i in range(len(nums)):
if nums[i] in dict1:
return [dict1[nums[i]],i]
else:
dict1[target-nums[i]] = i
if __name__ =="__main__":
s=Solution()
s.twoSum([2,7,11,15],9)
python
运行
"""双指针"""
class Solution:
def twoSum(self,nums,target):
l=len(nums)
array = list(zip(nums,range(l)))
array.sort()
low=0
high=l-1
while low<high:
S=array[low][0]+array[high][0]
if S<target:
low += 1
elif S>target:
high -= 1
else:
return [array[low][1],array[high][1]]
python
运行

