Reputation: 117
I've written the following code, and i was puzzled about how to calculate the time complexity of this code.
I think its O(n)
but my friend says otherwise. What do you think?
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;
}
}
Upvotes: 0
Views: 102
Reputation: 5649
The complexity is O(N*M). The complexity of outer for loop is N multiplied by M of inner for loop.
Upvotes: 1