给定一个整数数组,返回两个数字的索引,使它们相加到特定目标target。
解题思路1:python
利用键值进行匹配
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums)<=1:
return false
buff_dict={} //使用键-值(key-value)存储
for i in range(len(nums)):
if nums[i] in buff_dict: //如果当前数组值是待匹配的,则输出当前两个索引值
return [buff_dict[nums[i]],i]
else:
buff_dict[target-nums[i]]=i //键是剩下要匹配的数值,值是当前数值的索引
解题思路2:C++
c++ STL库里有自定义的hash_map 方法,有find(),insert()函数
--小白看不太懂 后续添加