本次挑战中,你需要在 sum.py 文件中补充函数 two_sum 的空缺部分。
1two_sum 函数接受两个参数,nums 用于指定传入的数组,val 用于指定和的值; 2two_sum 函数输出含两个索引的数组,或者 TypeError、 ValueError。
你需要补充 two_sum 函数,使 two_sum 函数可以找到数组 nums 中两个总和为 val 的值的索引。要求如下:
1对于传入的数组 nums,返回总和为 val 的两个值的索引; 2如果数组中没有和为目标值的元素,则返回 None。 3如果传入的数组 nums 或者目标值 val 为 None,需要使用 raise 语句显示 TypeError。 4如果传入的数组为空数组,需要使用 raise 语句显示 ValueError。
1class Solution(object): 2 3 def two_sum(self, nums, val): 4 if nums is None or val is None: 5 raise TypeError('nums or target cannot be None') 6 if not nums: 7 raise ValueError('nums cannot be empty') 8 cache = {} 9 for index, num in enumerate(nums): 10 cache_val = val - num 11 if num in cache: 12 return [cache[num], index] 13 else: 14 cache[cache_val] = index 15 return None
