一、问题描述
二、解题思路
这道题:exactly one solution,所以:1)不必考虑多解情况;2)不必考虑无解的异常处理。
方法一:暴力搜索
直接依次进行比较,时间复杂度O(n2):
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
for m,x in enumerate(nums[0:-1]):
for n,y in enumerate(nums[(m+1):]):
res = (target-y)
if x == res:
return m,n+m+1
用时过长:
当然也可以先排序,再利用首/尾移动查找,复杂付O(n*logn)
方法二:哈希表(O(n))
class Solution(object):
def twoSum(self, nums, target):
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
class Solution(object):
def twoSum(self,nums, target):
dic = dict(((v, i) for i, v in enumerate(nums)))
return next(( (i, dic.get(target-v))
for i, v in enumerate(nums)
if dic.get(target-v, i) != i), None)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for n,x in enumerate(nums):
try:
return dic[x] , n
except KeyError:
dic.setdefault(target - x,n)
知识点:
- 在读取dict的key和value时,如果key不存在,就会触发KeyError错误
- 利用next或者for进行遍历,迭代器对象从第一个元素开始访问,直到所有的元素被访问完结束,迭代器只前进不后退。
- 生成字典:
- dic = dict(((v, i) for i, v in enumerate(nums)))
- dic.setdefault(target - x,n)
- 位置1到末尾:enumerate(nums[0:-1])