题目描述:
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].
这道题主要用的还是Python的内置函数index()
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
re = [0,0]
for i in range(len(nums)):
if (target - nums[i]) in nums[i+1:]:
re[0] = i
re[1] = nums[i+1:].index(target-nums[i])+(i+1)
return re
我觉得这个方法还是挺简单的。就是效率低,不过代码短。又好理解。
这里再记录两个Python里的常用函数:
map(f,nums)
第一个参数是一个函数f,作用在num的每一个元素上。
>>> e = list(range(10))
>>> def f(num):
... return num+2
...
>>> list(map(f,e))
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>>
第二个函数是enumerate(nums),可以将Index和item一起输出
>>> list1 = [10,11,12,13,14]
>>> for index,item in enumerate(list1):
... print(index,item)
...
0 10
1 11
2 12
3 13
4 14
>>>