两数之和

给你一个有序列表(升序),一个目标值。写代码返回列表中和为目标值的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)
posted @ 2022-08-24 22:58  Ray_chen  阅读(10)  评论(0编辑  收藏  举报