求助:分析给定Python函数的Big O时间复杂度
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

