```python
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
n = [i for i in range(len(nums))]
nums_dict = dict(zip(nums, n)) # 创建字典
for i in range(len(nums)):
add = target - nums[i]
if add in nums_dict and nums_dict[add] != i: # 判断数字是否在字典里,且不是重复的数
return [i, nums_dict[add]]
结果输出:![在这里插入图片描述](https://img-blog.csdnimg.cn/20200301205427362.png)
用空间换取了一定的速度。时间复杂度为O(n)。