java - 这两个for循环的复杂度是多少?

标签 java algorithm complexity-theory

这个算法的时间复杂度是多少?我最初的猜测是 O(log[n])?

int array[] = new int[100];
int counter = 0;

for ( int i = 0; i < array.length; i++ ) {
    for ( int j = i + 1; j < array.length; j++ ) {
        if ( array[i] == array[j] ) {
            counter++;
        }
    }
}

最佳答案

代码中的 if 部分执行了大约 1 + 2 + 3 +...+ n 次(n - i - 1 其中 i = 0...n - 1,等于 0,5*n*(n+1),即 O(n^ 2)

关于java - 这两个for循环的复杂度是多少?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18811919/

相关文章:

java - Spring Boot - 源不能为空

java - 使用 OpenSSL (RSA-2048 Public-/Private-Key) 解密已非对称加密 (AES-256) 的 Java 文件

algorithm - Haskell 中的 Knuth-Morris-Pratt 实现——索引越界

c - 为什么这段代码的时间复杂度是 O(n) 而不是 O(n^2)?

java - org.hibernate.hql.internal.ast.QuerySyntaxException : Data is not mapped [from Data]

java - Spring ,CGLIB : why can't a generic class be proxied?

algorithm - 当时间复杂度根据 n 为偶/奇而变化时,算法 S 的最佳和最坏情况时间

algorithm - 奇怪排序的递归关系

python - 解释了两种不同合并排序实现之间的比较

binary-tree - 计算所有结构不同的二叉树的数量的时间复杂度是多少?