V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
dxandlight
V2EX  ›  Python

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

  •  
  •   dxandlight · 2018-08-16 11:28:44 +08:00 · 2419 次点击
    这是一个创建于 2051 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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
    3 条回复    2018-08-17 13:04:13 +08:00
    xxxy
        1
    xxxy  
       2018-08-16 11:57:56 +08:00
    按代码格式贴吧
    lecher23
        2
    lecher23  
       2018-08-16 15:54:47 +08:00   ❤️ 1
    感觉是 range 函数的问题吧,2.7 中 range 函数是先在内存中生成整个列表再遍历的,缺点是占内存,但是效率高,在 3 中 range 函数是一个生成器,内存占用小,但是效率低一点
    楼主可以在 2.7 版本中将 range 改成 xrang 试试会不会超时,如果超时基本可以确定是这个问题了
    HelloAmadeus
        3
    HelloAmadeus  
       2018-08-17 13:04:13 +08:00 via Android
    Python3.6 版本性能才赶得上 Python2.7,估计是 Python3 版本问题
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1236 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 18:01 · PVG 02:01 · LAX 11:01 · JFK 14:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.