两数之和
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中
这篇博客介绍了两种解决两数之和问题的方法。第一种是暴力求解,通过双层循环检查所有可能的数对组合。第二种是使用哈希表,遍历列表时查找目标值减当前数是否存在哈希表中,从而提高查找效率。这种方法减少了时间复杂度,提高了算法性能。
1万+

被折叠的 条评论
为什么被折叠?



