leetcode 1 两数相加
题目分析
https://leetcode-cn.com/problems/two-sum/
可以采取O(n^2)的两次遍历,也可以使用O(n)的hash法,遍历的过程中将遍历过的元素加入hash表中即可。
关于hash为什么判断某个key值是否存在于hash表中的复杂度为O(1),可以认为根据key值取value值的复杂度为O(1),那么判断key值是否存在于hash表中可以认为是根据这个key值获取value,获取到value则key值存在,否则key值不存在。
https://www.jianshu.com/p/55ecbc03c8c1
代码
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
dic = {}
for i in range(len(nums)):
if (target-nums[i]) in dic:
res = [i,dic[target-nums[i]]]
res.sort()
return res
else:
dic[nums[i]] = i
return []
68MS 14.8MB