我的功能的复杂性是什么?

时间:2014-01-11 14:22:14

标签: 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 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;
}

1 个答案:

答案 0 :(得分:1)

我会说O(log2(n)):

  1. 第一个循环执行log2(n)max iterations
  2. 第二循环取决于k < log2(n)并执行max log2(k)操作
相关问题