Problem: 1. 两数之和
思路
采用空间换时间,构造一个最大为10^4个元素的字典,遍历数组,将数组值和索引作为键值,若target-当前值在字典中出现,则当前位置和字典的值就是所需结果
解题方法
同上
复杂度
时间复杂度:
O ( n ) O(n) O(n)
空间复杂度:
O ( n ) O(n) O(n)
Code
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i, n in enumerate(nums):
if dic.get(target-n) is not None:
return [dic[target-n], i]
else:
dic[n] = i