难度: Easy
原题连接
内容描述
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(N)******
可以用O(n^2) loop
但是也可以牺牲空间换取时间,异常聪明的AC解法
2 7 11 15
不存在 存在之中
lookup {2:0} [0,1]
- 建立字典 lookup 存放第一个数字,并存放该数字的 index
- 判断 lookup 种是否存在:
target - 当前数字
, 则表面 当前值和 lookup中的值加和为 target. - 如果存在,则返回:
target - 当前数字
的 index 和 当前值的 index
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
look_up = {}
for i, num in enumerate(nums):
if target-num in look_up:
return [look_up[target-num], i]
look_up[num] = i
return []