给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例:
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
一开始遇到这个题目的想法就是笨方法:遍历,一个一个加呗。
反正c++ 忘得差不多了,上个python代码
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for i in range(len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return i,j
这个方法我觉得好low啊,for越多越冗长。
算了,就这样吧,网上方法大同小异
今天我发现一个这个函数,enumerate
例子如下
>>>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')]
以前就看到过,第一次正式使用
修改后的代码:
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for index,num in enumerate(nums):
if num in dic:
return(dic[num],index)
else:
dic[target - num] = index
这个代码牛逼在用了字典和enumerate(枚举)