V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
way2explore2
V2EX  ›  编程

时间复杂度?这段代码的时间复杂度?

  •  
  •   way2explore2 · Jun 4, 2021 · 2120 views
    This topic created in 1790 days ago, the information mentioned may be changed or developed.
    result = []
    for i in n:
      for jj in range(len(m)):
        if jj < 3:
          result.append((n,m))
        else:
          jj = len(m)
    

    n and m are two Python array.

    时间复杂度是多少呢?

    • O(n*m) 因为是嵌套循环
    • O(n) 因为 inner loop is fixed always 3
    • 其他?

    讨论一下?

    7 replies    2021-06-04 10:40:30 +08:00
    kuangwinnie
        1
    kuangwinnie  
       Jun 4, 2021
    ??这难道不是取决于你 m 是不是定值吗
    jhdxr
        2
    jhdxr  
       Jun 4, 2021   ❤️ 1
    『 O(n) 因为 inner loop is fixed always 3 』是错的
    例如 m 的长度是 10,尽管你 result 只`append`了 3 次,但你的`jj=len(m)`会执行 7 次
    polaa
        3
    polaa  
       Jun 4, 2021
    O(n*len(m))
    FurN1
        4
    FurN1  
       Jun 4, 2021   ❤️ 1
    0
    因为两个空格缩进的 Python 跑不了
    rrfeng
        5
    rrfeng  
       Jun 4, 2021
    @IgniteWhite 哈哈哈哈哈哈,启动解释器和读取文件的时间不算了吗
    delacey
        6
    delacey  
       Jun 4, 2021
    @rrfeng 时间复杂度不计算常量部分
    way2explore2
        7
    way2explore2  
    OP
       Jun 4, 2021   ❤️ 1
    @jhdxr 感謝慧眼識真,發現問題所在。

    哈哈
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3989 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 00:52 · PVG 08:52 · LAX 17:52 · JFK 20:52
    ♥ Do have faith in what you're doing.