(1)-LeetCode-两数之和(Two Sum)-python
- 题目如下
- 原代码
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
'''if判断
0+1,0+2,0+3,1+2,1+3,2+3
for循环
'''
x = []
for i in range(0, len(nums)):
for a in range(i + 1, len(nums)):
if nums[i] + nums[a] == target:
x = [i, a]
return x
break
else:
continue
在运行后,发现运行的时间太长
- 改进的代码
这个解法取自排名靠前的答案
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
'''if判断
0+1,0+2,0+3,1+2,1+3,2+3
for循环
'''
#定义一个空字典
q = {}
for i in range(len(nums)):
a = target - nums[i]
#如果字典中有nums[i]
if nums[i] in q:
return q[nums[i]],i
#否则就往字典中添加键值对
else:
q[a] = i
a = Solution()
q = [2,7,11,15]
a.twoSum(q,9)
在程序前期思考中,要考虑程序的时间复杂度