给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = {} #创建空字典
for index, num in enumerate(nums):#从前往后,逐个存入字典,让后面的数找到前面的数
another_num = target - num
if another_num in hashmap:
return [hashmap[another_num], index]
hashmap[num] = index #将num输入字典,建立num:index,这样取数就可以根据num取出下标
return None
enumerate(sequence, [start=0])
参数:
1.sequence – 一个序列、迭代器或其他支持迭代对象。
2.start – 下标起始位置。
该函数是枚举列举的意思,同时列出数据下标和数据
如下
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) # 下标从 1 开始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
注意:该函数枚举时,是按 ” 下标:数据 “ 建立
另外找了一些建立字典的方法
声明:转自优快云 (http://blog.youkuaiyun.com/csujiangyu/article/details/45176399)
1.创建空字典
>>> dic = {}
>>> type(dic)
<type 'dict'>
2.直接赋值创建
>>> dic = {'spam':1, 'egg':2, 'bar':3}
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
3.通过关键字dict和关键字参数创建
>>> dic = dict(spam = 1, egg = 2, bar =3)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
4.通过二元组列表创建
>>> list = [('spam', 1), ('egg', 2), ('bar', 3)]
>>> dic = dict(list)
>>> dic
{'bar': 3, 'egg': 2, 'spam': 1}
5.dict和zip结合创建
>>> dic = dict(zip('abc', [1, 2, 3]))
>>> dic
{'a': 1, 'c': 3, 'b': 2}
6.通过字典推导式创建
>>> dic = {i:2*i for i in range(3)}
>>> dic
{0: 0, 1: 2, 2: 4}
7.通过dict.fromkeys()创建
通常用来初始化字典, 设置value的默认值
>>> dic = dict.fromkeys(range(3), 'x')
>>> dic
{0: 'x', 1: 'x', 2: 'x'}
8.其他
>>> list = ['x', 1, 'y', 2, 'z', 3]
>>> dic = dict(zip(list[::2], list[1::2]))
>>> dic
{'y': 2, 'x': 1, 'z': 3}