两数之和
1.题目描述
class Solution:
def twoSum(self, nums, target):
length = len(nums)
for i in range(length):
for j in range(i + 1, length):
if nums[i] + nums[j] == target:
return [i, j]
思路:暴力求解
def twoNum1(nums, target):
"""
哈希表法
:param nums:
:param target:
:return:
"""
length = len(nums)
hash = dict()
for i in range(length):
# if len(hash) == 0:
# hash[nums[0]] = 0
val = target - nums[i]
if val in hash:
return [hash[val], i]
else:
hash[nums[i]] = i
return []
思路:针对列表中的每个数nums[i] 均计算target-i的值并在dict中查找是否有key值为target - nums[i]的键值对存在,如果有则返回[i,dict[target - nums[i]]]。反之,若不存在则将target - nums[i]作为key,下标i作为value存入dict中