You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:分析给定Python函数的Big O时间复杂度

Analyzing the Big O Complexity of Your Function

Let’s break this down step by step—we’ll focus on counting the core operations to find the growth rate, no overcomplicated jargon needed.

First, here’s your function for easy reference:

def complexity(n):
    k = 0
    for i in range(2, n):
        for j in range(n, 2*n):
            k = k+1

Step 1: Break down the outer loop

The outer loop runs from i=2 to i=n-1 (since Python’s range is left-inclusive, right-exclusive). That’s a total of n - 2 iterations. When calculating Big O, we ignore constant terms because they don’t impact the growth rate as n becomes very large. So this loop contributes O(n) complexity.

Step 2: Break down the inner loop

The inner loop runs from j=n to j=2n-1. Let’s count the iterations: 2n - n = n total runs. No constants to factor out here—this loop also contributes O(n) complexity.

Step 3: Combine nested loops

For nested loops, you multiply the complexity of each loop. Every iteration of the outer loop triggers a full run of the inner loop. So total operations are roughly n * n = n². Dropping lower-order terms and constants, the overall time complexity is O(n²).

Match to the given options

Looking at your choices:

  • (a) O(n³) → Incorrect
  • (b) O(n²) → Correct
  • (c) O(n) → Incorrect
  • (d) O(nlogn) → Incorrect
  • (e) None of the above → Incorrect

内容的提问来源于stack exchange,提问作者LeoT2020

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:41:09