运用哈希表
class Solution:
def twoSum(nums, target):
hashtable = dict()
for i, num in enumerate(nums):
if target - num in hashtable:
return [hashtable[target - num], i]
hashtable[nums[i]] = i
print(hashtable)
return []
nums = [i for i in range(1,7)]
print('result:{}'.format(Solution.twoSum(nums,10)))
复杂度分析:
- 时间复杂度:O(N),其中 NN 是数组中的元素数量。对于每一个元素 x,我们可以 O(1)地寻找 target - num。
- 空间复杂度:O(N),其中 NN 是数组中的元素数量。主要为哈希表的开销。