返回信息流代码小白。代码二执行的时候时间超时,下面两段代码if执行时有什么区别?其他部分都是一样的。谢谢~
#####################代码一##########################
class Solution(object):
def threeSum(self, nums):
nums.sort()
res = []
for i in range(len(nums)-2):
if i == 0 or i > 0 and nums[i] != nums[i-1]:
left = i + 1
right = len(nums) - 1
while left < right:
s = nums[i] + nums[left] + nums[right]
if s == 0:
res.append([nums[i], nums[left], nums[right]])
left = left + 1
right = right -1
while left < right and nums[left] == nums[left-1]:
left = left + 1
while left < right and nums[right] == nums[right+1]:
right = right - 1
elif s < 0:
left = left + 1
else:
right = right - 1
return res
###################################代码二分割线#############################################
class Solution(object):
def threeSum(self, nums):
result = []
nums.sort()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l = i + 1 #l is left
r = len(nums) - 1 #r is right
while l < r:
s = [nums[i] ,nums[l] ,nums[r]]
if sum(s) == 0:
result.append(s)
l = l + 1
r = r - 1
while l < r and nums[l] == nums[l - 1]:
l = l + 1
while l < r and nums[r] == nums[r + 1]:
r = r - 1
elif sum(s) > 0:
r = r - 1
else:
l = l + 1
return result
这是一条镜像帖。来源:北邮人论坛 / python / #19148同步于 2017/9/7
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Python机器人发帖
【问题】LeetCode Python 时间超时
TTong
2017/9/7镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
猜测问题应该是代码2中求了两次sum(s),为了测试,将代码2修改如下:
```
class Solution(object):
def threeSum(self, nums):
result = []
nums.sort()
for i in range(len(nums)-2):
if i > 0 and nums[i] == nums[i-1]:
continue
l = i + 1 #l is left
r = len(nums) - 1 #r is right
while l < r:
s = nums[i] + nums[l] + nums[r]
if s == 0:
result.append([nums[i], nums[l], nums[r]])
l = l + 1
r = r - 1
while l < r and nums[l] == nums[l - 1]:
l = l + 1
while l < r and nums[r] == nums[r + 1]:
r = r - 1
elif s > 0:
r = r - 1
else:
l = l + 1
return result
```
ac了,耗时1056ms
【 在 TTong 的大作中提到: 】
: 代码小白。代码二执行的时候时间超时,下面两段代码if执行时有什么区别?其他部分都是一样的。谢谢~
: #####################代码一##########################
: class Solution(object):
: ...................
知道问题所在了,非常感谢~
【 在 moewifj 的大作中提到: 】
: 猜测问题应该是代码2中求了两次sum(s),为了测试,将代码2修改如下:
: [md]
: ```
: ...................