题目
https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
思路
如果是遍历一遍nums,再判断targe - num是否出现在nums中(in操作是O(n)的时间复杂度),这样时间复杂度是
如何优化?空间换时间。每次遍历,用hash_map存储当前值和索引(因为要返回索引),然后在hash_map中查找。hash_map中查找的时间复杂度是。
代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hash_map = {}
for i, num in enumerate(nums):
if target - num in hash_map:
return [i, hash_map[target-num]]
else:
hash_map[num] = i