刷 leetecode 的时候发现同样一段代码,用 Python 通过了,用 py3 就超时,这段代码有什么问题吗?

2018-08-16 11:28:44 +08:00
 dxandlight
rt 附上代码,求大神解答。
class Solution:
# @return a list of lists of length 3, [[val1,val2,val3]]
def threeSum(self, num):
num.sort()
res = []
for i in range(len(num)-2):
if i == 0 or num[i] > num[i-1]:
left = i + 1
right = len(num) - 1
while left < right:
if num[left] + num[right] == -num[i]:
res.append([num[i], num[left], num[right]])
left += 1
right -= 1
while left < right and num[left] == num[left-1]:
left += 1
while left < right and num[right] == num[right+1]:
right -= 1
elif num[left] + num[right] < -num[i]:
while left < right:
left += 1
if num[left] > num[left-1]:
break
else:
while left < right:
right -= 1
if num[right] < num[right+1]:
break
return res
2472 次点击
所在节点    Python
3 条回复
xxxy
2018-08-16 11:57:56 +08:00
按代码格式贴吧
lecher23
2018-08-16 15:54:47 +08:00
感觉是 range 函数的问题吧,2.7 中 range 函数是先在内存中生成整个列表再遍历的,缺点是占内存,但是效率高,在 3 中 range 函数是一个生成器,内存占用小,但是效率低一点
楼主可以在 2.7 版本中将 range 改成 xrang 试试会不会超时,如果超时基本可以确定是这个问题了
HelloAmadeus
2018-08-17 13:04:13 +08:00
Python3.6 版本性能才赶得上 Python2.7,估计是 Python3 版本问题

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/480322

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX