for循环或while循环的时间复杂度

huangapple go评论69阅读模式
英文:

Time complexity of a for or while loop

问题

以下是翻译好的部分:

"The time complexity of a for loop with n as the input is O(n) from what I've understood till now but what about the code inside the loop?"

"for循环的时间复杂度,以n作为输入,根据我现在的理解是O(n),但循环内的代码呢?"

    arr.remove(var)

"arr is a list with n elements and var can be a string or a number."

"arr是一个包含n个元素的列表,而var可以是字符串或数字。"

"How do I know if I should multiply or add time complexities? Is the time complexity of the above code O(n**2) or O(n)?"

"我如何知道是要相乘还是相加时间复杂度?上面的代码的时间复杂度是O(n**2)还是O(n)?"

    arr.remove(var)
    arr.remove(var1)

"What would the time complexity be now? What should I add or multiply?"

"现在的时间复杂度是多少?我应该相加还是相乘?"

"I tried learning about time complexity but couldn't understand how to deal with code having more than one time complexity."

"我尝试学习时间复杂度,但无法理解如何处理具有多个时间复杂度的代码。"

英文:

The time complexity of a for loop with n as the input is O(n) from what I've understood till now but what about the code inside the loop?

while var in arr:
    arr.remove(var)
    

arr is a list with n elements and var can be a string or a number.

How do I know if I should multiply or add time complexities? Is the time complexity of the above code O(n**2) or O(n)?

for i in range(n):
    arr.remove(var)
    arr.remove(var1)

What would the time complexity be now? What should I add or multiply?

I tried learning about time complexity but couldn't understand how to deal with code having more than one time complexity.

答案1

得分: 2

在循环内部内容中你需要了解时间复杂度

```python
for i in arr:  # O(n) 
    print(sum(arr) - i)  # O(n)

在这种情况下,.pop(0) 嵌套在循环内部,所以你需要将复杂度乘以循环的复杂度:O(n) * O(n) > O(n*n) > O(n²)。

for i in arr:  # O(n) 
    print(sum(arr) - i)  # O(n)
    print(sum(arr) - i)  # O(n)

在这种情况下,它是

O(n) * (O(n) + O(n))
O(n) * O(n+n)
O(n) * O(2n)
O(n) * O(n)
O(n*n)
O(n²)

查看更多关于时间复杂度计算中何时添加和何时相乘的信息,请参考 When to add and when to multiply to find time complexity

对于 while 循环,它不会改变任何内容:将内容与 while 的复杂度相乘。


<details>
<summary>英文:</summary>

You need to know the time complexity of the content inside the loop.

```python
for i in arr:  # O(n) 
    print(sum(arr) - i)  # O(n)

In this case, the .pop(0) is nested in the forloop, so you need to multiply the complexity to the forloop complexity: O(n) * O(n) > O(n*n) > O(n²).

for i in arr:  # O(n) 
    print(sum(arr) - i)  # O(n)
    print(sum(arr) - i)  # O(n)

In this case, it's

O(n) * (O(n) + O(n))
O(n) * O(n+n)
O(n) * O(2n)
O(n) * O(n)
O(n*n)
O(n&#178;)

See When to add and when to multiply to find time complexity for more information about that.

For a while loop, it doesn't change anything: multiply content with the complexity of the while.

huangapple
  • 本文由 发表于 2023年2月8日 19:04:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定