最近,我开始回顾有关Big O表示法的问题,并且遇到了一个非常简单的问题。 实际上,我有点困惑,如果有人可以给我详细说明,那会很棒。
查看下面的伪代码:
Boolean: ContainsDuplicates(Integer: array[])
// Loop over all of the array's items except the last one.
For i = 0 To <largest index> - 1
// Loop over the items after item i.
For j = i + 1 To <largest index> N
// See if these two items are duplicates.
If (array[i] == array[j]) Then Return True
Next j
Next i
// If we get to this point, there are no duplicates.
Return False
End ContainsDuplicates
我想了解哪个大O代表下面的循环,因为j的初始值为i + 1:
对于j = i + 1到N
谢谢
答案 0 :(得分:1)
您看到任何图案吗? 就像做1 + 2 + 3 + ... +(N-1)+ N
达到此目的的公式是(N + 1)(N)/ 2
Big O表示法相当于N²
答案 1 :(得分:0)
谢谢。我正在读一本书,有两种不同的方法。 第一个如下所述:
Boolean: ContainsDuplicates(Integer: array[])
// Loop over all of the array's items.
For i = 0 To <largest index>
For j = 0 To <largest index>
// See if these two items are duplicates.
If (i != j) Then
If (array[i] == array[j]) Then Return True
End If
Next j
Next i
// If we get to this point, there are no duplicates.
Return False
End ContainsDuplicates
and then there is the other shared here as:
Boolean: ContainsDuplicates(Integer: array[])
// Loop over all of the array's items except the last one.
For i = 0 To <largest index> - 1
// Loop over the items after item i.
For j = i + 1 To <largest index> N
// See if these two items are duplicates.
If (array[i] == array[j]) Then Return True
Next j
Next i
// If we get to this point, there are no duplicates.
Return False
End ContainsDuplicates
我猜这两个结果都一样,即N²对吧?