给定一个数组和一个target,求出满足数组中满足两个数之和等于target的数的下标
方法一:
第一个想到的肯定是hash表,python里面是字典,遍历一遍即可,放入的同时检查target减去放入的元素是否在hash表中
python
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dictionary = {}
for i in range(len(nums)):
if target-nums[i] in dictionary:
return [i,dictionary[target-nums[i]]]
else :
dictionary[nums[i]] = i
return [0,0]
beat 83.92%
如果在遍历的过程中加点修改,省去根据i找nums[i]的过程
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dictionary = {}
for i,num in enumerate(nums):
if target - num in dictionary:
return [i,dictionary[target-num]]
dictionary[num] = i
return [0, 0]
wtf,还是beat 83.92%