开始之前:从2018/8/27开始刷LeetCode,计划每周刷五题,周末进行总结并发布在csdn上,计划先刷150道题,从简单开始。
week 1-1
要求:
CODE:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i,num in enumerate(nums):
# 如果dict中不存在现在的数字,则将其希望匹配的数字和当前索引存入dict
# [匹配值,当前索引]
if num not in dic:
dic[target-num] = i
# 如果dict中存在现在的数字,返回 [匹配索引,原索引]
else:
return [dic[num],i]
结果:
知识点:
1. 枚举 enumerate
1. 用于for循环
2. 后面跟序列、迭代器等可迭代对象
eg. for i,num in enumerate(nums):
2. key in dict: 判断键是否存在于字典中
eg. if 3 in dic: 判断是否有3未键的记录存在于字典dic中