java - 在 for 循环内的 if that 内包含 2 个 for 循环的代码的复杂性是多少

标签 java for-loop time-complexity

我写了下面的代码,我很困惑如何计算这段代码的时间复杂度。

我认为它是O(n),但我的 friend 说不然。你觉得怎么样?

public class Matrix {

    public static int hole(int[][]mat)
    {
        int col=0;
        int count1 = 0;
        int count0=0;
        for(int k=0;k<mat[0].length;k++)
        {
            count0 = 0;
            count1 = 0;

            if (mat[k][k] == 0)
            {
                // search column for ones
                for (int j = 0; j < mat.length; j++)
                {
                    if (mat[j][k] == 0 && j == k)
                        continue;
                    else if (mat[j][k] == 1)
                    {
                        count1++;
                    }
                    else
                        break;
                }
                //search the row
                for(int row = 0;row<mat.length;row++)
                {
                    if(mat[k][row]==0)
                    {
                        count0++;
                    }
                    else
                        break;
                }
                if(count0==mat.length&&count1==mat.length-1)
                {
                    return k;
                }
                
                
            }
            
        }
        System.out.print(count0 +"\n" +count1);
        return -1;
    }

}

最佳答案

复杂度为O(N*M)。外层for循环的复杂度是N乘以内层for循环的M。

关于java - 在 for 循环内的 if that 内包含 2 个 for 循环的代码的复杂性是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41285280/

相关文章:

algorithm - 时间复杂度作为输入位数的函数来衡量?

java - 为什么应该尝试抛出未经检查的异常而不是已检查的异常?

Python 导出一些列表并将所有列表放入 for 循环中

python-3.x - 函数调用中的Python循环列表

python - 可以像在 Python 中一样在 MATLAB 中完成并行遍历吗?

python - 以下代码的时间复杂度是多少? O(nlogn) 还是 O(N)?什么时候复杂度是O(nlogn)?

java - 相交圆重叠

java - 移动 arraylist 对象的动画

java - 转换后日出和日落时间相等

algorithm - For循环按变量递增,时间复杂度