algorithm - 大O : How to determine runtime for a for loop incrementation based on outer for loop?

标签 algorithm runtime time-complexity big-o

我有以下算法,运行时复杂度为 O(N^2) 但我想更深入地了解它,而不是仅仅记住常见的运行时。

考虑到内部 for 循环中使用 i+1 分解和分析它的正确方法是什么?

void printunorderedPairs(int[] array) {
    for(int i=0; i<array.length; i++) {
        for(int j=i+1; j<array.length; j++) {
            System.out.println(array[i] + "," + array[j]);
        }
    }
}

编辑

询问如何分析特定问题

最佳答案

What would be the right approach to break it down and analyze it

拿铅笔和纸,放下一些展开的环:

     i        inner loops per i
-------------------------------
     1               length - 1  
     2               length - 2
    ..                       ..  
     k               length - k 
    ..                       ..
length - 1                    1
length                        0

现在,为了获得所需的总时间,让我们总结一下内部循环:

 (length - 1) + (length - 2) + ... + (length - k) ... + 1 + 0

它是一个等差数列,它的和是

 ((length - 1) + 0) / 2 * length == length**2 / 2 - length / 2 = O(length**2)

关于algorithm - 大O : How to determine runtime for a for loop incrementation based on outer for loop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41407714/

相关文章:

algorithm - 如何找到节点之间的最短路径?

algorithm - 使用堆栈的 push & pop 操作实现队列

java - 检查数字的二进制表示形式中所有设置位后仅跟随未设置位的最佳方法

java - 这两个示例代码的时间复杂度是否不同,如何?

algorithm - 找到给定数字 'n' 的最快方法可以绝对表示为 2^m

visual-c++ - Is/nodefaultlib :msvcr100 the proper approach to handling msvcr100. dll vs msvcr100d.dll defaultlib 问题

c# - 使用 Silverlight 获取页面的 html 内容

python - 两个类似的实现退出运行时间差异巨大

algorithm - 复杂度为 O(n^5) 的算法示例是什么?

algorithm - 给定神奇数据结构的更快排序算法?