我写了下面的代码,我很困惑如何计算这段代码的时间复杂度。
我认为它是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/