###1. Two Sum
题目: https://leetcode.com/problems/two-sum/
难度:
Easy
思路
可以用O(n^2) loop
但是也可以牺牲空间换取时间,异常聪明的AC解法
2 7 11 15
不存在 存在之中
lookup {2:0} [0,1]
一点字典有了这个 target - 当前数字
,找到它的index和当前index一起返回。
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i, num in enumerate(nums):
if target - num in lookup:
return [lookup[target - num],i]
lookup[num] = i
return []