[英]Time complexity for 2 nested loops
If I'm taking input through 2 nested For-loops like this如果我通过 2 个这样的嵌套 For 循环输入
cin>>x;
for(i=0;i<x;i++)
{
cin>>y;
for(j=0;j<y;j++)
}
The complexity of the Outer loop is O(X) but I'm confused about the Time complexity of the inner loop as the Y is variable.外循环的复杂度是 O(X) 但我对内循环的时间复杂度感到困惑,因为 Y 是可变的。
The complexity of the outer loop is not O(x)
, because the time it takes to run the outer loop depends on the value of y entered.外循环的复杂性不是
O(x)
,因为运行外循环所需的时间取决于输入的 y 的值。
Let's say we have a sequence y1,y2,...,yn
of inputs for y.假设我们有一个
y1,y2,...,yn
的输入序列。 Then the first loop would take y1
operations and the second iteration would take y2
operations and so on for each of the x
iterations.然后第一个循环将进行
y1
次操作,第二次迭代将进行y2
次操作,依此类推,每次迭代x
次。
Now let Y
be the max of this sequence of inputs, then each iteration of the outer loop would take at most Y
operations.现在让
Y
是这个输入序列的最大值,那么外循环的每次迭代将最多进行Y
次操作。 So we have that for x
iterations each taking at most Y
operations we get O(xY).因此,对于
x
次迭代,每次最多进行Y
次操作,我们得到 O(xY)。
It is possible to specify further to a possibly smaller class of functions but it's important to remember that if f < g
then O(f)
is contained in O(g)
.可以进一步指定可能更小的 class 函数,但重要的是要记住,如果
f < g
则O(f)
包含在O(g)
中。 And that when we say a function is O(f)
we just mean it is inside the class O(f)
.当我们说 function 是
O(f)
时,我们只是说它在 class O(f)
内部。
Considering in this case the input is not determined using the max would be a worst case scenario.考虑到在这种情况下,输入不是使用最大值确定的,这将是最坏的情况。
Also it would be more accurate if the input was outside all the loops as input isn't a constant operation most of the time.如果输入在所有循环之外,它也会更准确,因为输入在大多数情况下都不是一个恒定的操作。 (This is trivial though, just have the y be input from a file or something and then use that to make an array.)
(虽然这很简单,只需从文件或其他东西输入 y ,然后用它来制作数组。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.