[英]What is Big O in this example of code, O(N) or O(N^2)?
Can you please explain what is Big O in this example of code?你能解释一下这个代码示例中的 Big O 是什么吗?
arr = [
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1],
[1, 1]
]
def count_ones(outer_array):
count = 0
for inner_array in outer_array:
for number in inner_array:
count += 1
return count
count_ones(arr)
It depends entirely on your definition of n
.这完全取决于您对
n
的定义。 If you define n
to be the number of cells in the 2d matrix, then this nested loop is of linear complexity O(n)
in relation to it.如果您将
n
定义为 2d 矩阵中的单元格数,则此嵌套循环的线性复杂度为O(n)
。
On the other hand, if you define n
to be the length of the outer array and m
the maximum length of the inner arrays then the time complexity is O(n*m)
.另一方面,如果您将
n
定义为外部数组的长度,而m
定义为内部数组的最大长度,则时间复杂度为O(n*m)
。
Either way, the complexity can't be O(n^2)
since in that case it needs to be a square matrix with sides of equal length n
.无论哪种方式,复杂度都不能是
O(n^2)
因为在这种情况下,它需要是边长相等的方阵n
。
Given that n is defined as the total number of elements in the nested array:鉴于 n 被定义为嵌套数组中元素的总数:
for inner_array in outer_array:
for number in inner_array:
is O(n) since it visits every element once.是 O(n),因为它访问每个元素一次。
count += 1
is O(1) since it is basic arithmetic.是 O(1) 因为它是基本算术。
O(1) * O(n) = O(n) O(1) * O(n) = O(n)
Basically, you have 2-dimension array and every element picks once.基本上,你有一个二维数组,每个元素都选择一次。 In common case it's O(N), where N - number of elements.
通常情况下它是 O(N),其中 N - 元素数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.