在编写leecode上的算法第一题“两数之和”时,遇到了一些问题,如下:
1.参数丢失
>>>Solution.twosum([2,3,4,5],8)
TypeError: twosum() missing 1 required positional argument: 'target'
原因:没有创建对象
解决:
>>>a = Solution() #括号很重要
>>>a.twosum([2,3,4,5],8)
2.超出时间显示
原因:时间复杂度高 O(n2)
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
i = 0
n = len(nums)
while i < n:
j = i+1
while j <n:
if nums[i] + nums[j] == target:
return [i,j]
j += 1
i += 1
解决: 降低时间复杂度,O(n)
class Solution:
def twoSum(self,nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
#用len()方法取得nums列表长度
n = len(nums)
#创建一个空字典
d = {}
for x in range(n):
a = target - nums[x]
#字典d中存在nums[x]时
if nums[x] in d:
return d[nums[x]],x
#否则往字典增加键/值对
else:
d[a] = x
#边往字典增加键/值对,边与nums[x]进行对比