两数的和

题目

代码

class TwoSum:
    def __init__(self,nums,target):
        self.nums = nums
        self.target = target
    def sum(self):
        hash_dict = { }
        for index, value in enumerate(self.nums):
            # 在字典中查询其差值是否在字典中
            if hash_dict.get(self.target - value) is not None:    
                #如果在字典中,通过get方法找到差值的索引
                return [hash_dict.get(self.target - value), index] 
           # 如果差值不在字典中,将其元素作为键,其索引作为值存入字典
            hash_dict[value] = index  
            
nums =  list(map(int,input("Enter nums:\n").split( )))
target =  int(input("Enter target:\n"))  
num =  TwoSum(nums,target).twosum() 
print(num)

输入

Enter nums:
0 2 3
Enter target:
5

输出

[1, 2]

posted @ 2020-05-05 17:18  sinlearn  阅读(217)  评论(0编辑  收藏  举报