给你一个有序列表(升序),一个目标值。写代码返回列表中和为目标值的2个数的下标(该组合唯一)
input [2,7,11,15], t = 18
output 1,2
双指针法
class Solution:
def two_sum(self,nums,t):
left = 0
right = len(nums) - 1
while left < right:
tmp = nums[left] + nums[right]
if tmp == t:
return left,right
elif tmp > t:
right -= 1
else:
left += 1
return None
nums = [2,7,11,15]
t = 18
Solution().two_sum(nums,t)
hashmap 方法
class Solution:
def two_sum(self,nums,t):
dict = {}
for i in range(len(nums)):
if t - nums[i] not in dict:
dict[nums[i]] = i
else:
return [dict[t-nums[i]],i]
nums = [2,7,11,15]
t = 18
Solution().two_sum(nums,t)