algorithm - 如何计算大 O 表示法中的时间复杂度以进行数组双重查找

标签 algorithm time-complexity big-o

以下算法的时间复杂度是多少??有人可以帮忙吗

public class Util
{

    public static int GetDistance(int[] array)
    {
        //Find the max seperation of two same numbers inside an array for example 
        // {1,2,4,1,5,9,0,4,15,1,2} should return 9 ( position of '1' at 9th and 0th location)

        int N = array.Length;
        int maxDistance=0;
        for (int i = 0; i < N; i++)
        {
            for (int j = (N-1); j > i; j--) 
             {
                 if (array[j]==array[i])   
                    if(maxDistance < (j-i))
                        maxDistance = j- i;
             }//End of inner for

        }//End of for
        System.Console.WriteLine("maxDistance " + maxDistance);
        return maxDistance ;
    } //End of Function

} //End of Class

最佳答案

你看内层循环(内层循环里面的操作需要常数时间)。内部循环恰好执行 N-1-i 次。

然后外层循环恰好执行 N 次,i 的值增加。总工作量涉及

(N-1) + (N-2) + (N-3) + ... + 1

内部 body 的处决。这个和是一个三角数,证明等于没什么大不了

(N-1).N / 2

这是 O(N²)。

关于algorithm - 如何计算大 O 表示法中的时间复杂度以进行数组双重查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38563460/

相关文章:

javascript - 比较 2 列表得到移动 id + 偏移量 + 方向

data-structures - 与哈希表相比,splay 树有哪些优势?

algorithm - 哈希算法的困惑

c++ - 下面代码的算法复杂度是多少

algorithm - 方差的渐近运行时间是多少?

无重排整数分区的JavaScript递归实现

c++ - 复杂的尾递归案例

算法:T(N) =2^N

c++ - Negamax 实现似乎不适用于井字游戏

data-structures - For 循环时间复杂度