Java 我的功能有多复杂?
我想找出我函数的复杂性,我不确定它是O(n)还是其他什么Java 我的功能有多复杂?,java,complexity-theory,Java,Complexity Theory,我想找出我函数的复杂性,我不确定它是O(n)还是其他什么 public static boolean find(int [][] mat, int x) { int i = 1; int j = 0; int k = 0; int row = 0; int col = 0; int n = mat.length; while(i < n)//(see method discription)stage 1. loops over max
public static boolean find(int [][] mat, int x)
{
int i = 1;
int j = 0;
int k = 0;
int row = 0;
int col = 0;
int n = mat.length;
while(i < n)//(see method discription)stage 1. loops over maxuim of n/2 times = O(n)
{
i = i * 2;
if(x == mat[i-1][i-1])
return true;
else if (x < mat[i-1][i-1])
{
k = i / 2;
row = col = i-1;
break; //bigger value then x found, x is within the max and min values of the matrix. moving on to find a match.
}
}
if (i > n)//x is bigger then max value of mat
return false;
for (j = k; j > 1; j = j / 2)//stage 2. locking on the right 2x2 matrix. runs k times. k<n O(n)
{
if(x == mat[row-j][col] || x == mat[row][col-j])
return true;
else if(x < mat[row-j][col])
row = row - j;
else if (x < mat[row][col-j])
col = col - j;
}
//checking if x is within this 2x2 matrix
if(x == mat[row][col-1])
return true;
else if(x == mat[row-1][col])
return true;
else if(x == mat[row-1][col-1])
return true;
else
return false;
}
公共静态布尔查找(int[][]mat,int x)
{
int i=1;
int j=0;
int k=0;
int行=0;
int col=0;
int n=材料长度;
而(in)//x大于mat的最大值
返回false;
对于(j=k;j>1;j=j/2)//第2阶段。锁定右侧2x2矩阵。运行k次。k我会说O(log2(n)):
第一个循环执行log2(n)个最大迭代
第二个循环依赖于k
这是O(n)
,你已经发现了。@RohitJain你是如何推断的?我所看到的是I=I*2(so O(log(n)),j=j/2(so也是O(log(k))@jbnitet是对的,它应该是O(log(n)),因为循环不是线性迭代的。@jbnitet.Oh.我错过了I=I*2
。