|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- def two_sum(self, nums, val):
- if nums is None or val is None:
- raise TypeError('heheh ')
- if not nums:
- raise ValueError('hahah ')
- cache = {}
- for index, num in enumerate(nums):
- cache_val = val - num
- if num in cache:
- return [cache[num], index]
- else:
- cache[cache_val] = index
- return None
复制代码
cache = {} 怎么和for语句关联的呀? for语句是创建了一个字典吗,怎么把项弄到cache里面的?
和 for 循环里面的 else 下面的代码块有关联
for语句是创建了一个字典吗,怎么把项弄到cache里面的?
字典是你之前 cache = {} 就创建了,是在 for 循环中添加字典中的元素
当 num 不在字典中时,就将执行 else 语句 往 cache = {} 字典里添加新的 键-值对 元素,也就是执行:cache[cache_val] = index
|
|