题目描述:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
分析:
- 可以内外循环两遍遍历nums数组,若他们的和为目标值target,则返回这两个数的下标索引。(暴力法)
- 查找一个元素是否存在于数组中最快的方法是,使用哈希表。故可以首先遍历数组nums建立一个哈希表,其存储nums数组及其一一对应的索引。然后再遍历nums的每一个元素n,检查target-n是否存在于哈希表中,若存在,则返回该元素n的索引以及target-n在哈希表中存储的索引。
方法:(1)暴力法(2)两遍哈希表
复杂度分析:
时间复杂度:O(n),我们把包含有 n个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1),所以时间复杂度为 O(n)。
空间复杂度:O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表中存储了n个元素。
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
hashmap = dict()
for i, n in enumerate(nums):
hashmap[n] = i
for j, n in enumerate(nums):
another_num = target-n
if hashmap.get(another_num) and hashmap.get(another_num) != j:
result = []
result.append(j)
result.append(hashmap.get(another_num))
return result