题目

https://leetcode-cn.com/problems/two-sum/
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

image.png

思路

如果是遍历一遍nums,再判断targe - num是否出现在nums中(in操作是O(n)的时间复杂度),这样时间复杂度是【LeetCode】1. 两数之和 - 图2

如何优化?空间换时间。每次遍历,用hash_map存储当前值和索引(因为要返回索引),然后在hash_map中查找。hash_map中查找的时间复杂度是【LeetCode】1. 两数之和 - 图3

代码

  1. class Solution:
  2. def twoSum(self, nums: List[int], target: int) -> List[int]:
  3. hash_map = {}
  4. for i, num in enumerate(nums):
  5. if target - num in hash_map:
  6. return [i, hash_map[target-num]]
  7. else:
  8. hash_map[num] = i