问题描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
知识点:
- enumarate用法
enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
通常在for 循环使用 enumerate
seq = [‘one’, ‘two’, ‘three’]
for i, element in enumerate(seq):
… print i, element
…
0 one
1 two
2 three
- 字典用法
建立一个字典,d = {},字典的key是数组的值num(key一般是已知确定的值,所以用num),value是相应的位置, 然后只要满足 num 和 target - num都在字典里面则找到答案。这种方法的时间复杂度是(O(n)) - self
只有在类的方法中才会有,独立的函数或方法是不必带有self的。所以self名称不是必须的。另外,self也不是作为参数传递使用的,当然也不是关键词,只是约定成俗的写法,可以用a或b,甚至将self改为myself一样没有错误。
self指的是类实例对象本身(注意:不是类本身),相当于Java 的this
Python解决方案1
class Solution(object):
def TwoSum(self, nums, target):
"""
:param nums: List[int]
:param target: int
:return: List[int]
"""
d = {}
for i, num in enumerate(nums):
if target - num in d:
return [d[target - num], i]
d[num] = i
Python解决方案2
class Solution(object):
def twoSum(self, nums, target):
dic = {}
for i, num in enumerate(nums):
if num in dic:
return [dic[num], i]
else:
dic[target - num] = i