以下算法的运行时间(例如来自破解编码面试的例子)

时间:2016-08-29 23:48:40

标签: algorithm

破解编码采访书的问题之一是询问以下算法的运行时间,该算法打印从1到n的2的幂:

int powersOf2(int n) {
    if (n < 1) return 0;
    else if (n == 1) print(1); return 1;
    else
    {
        int prev = powersOf2(n/2);
        int curr = prev * 2;
        print(curr); 
        return curr;
    }
}

作者回答它在O(log n)中运行。

这很有道理,但是... n是输入的值! (伪子线性运行时)。

说运行时间是否为O(m)更正确,其中m是算法输入的长度? (O(log(2 ^ m))= O(m))。

或者完全可以简单地说它在O(log n)中运行而不提及任何关于伪运行时的内容......

我正准备接受采访,并想知道我是否需要提及运行时间伪子线性,这类问题取决于输入值。

2 个答案:

答案 0 :(得分:2)

我认为你在这里寻找的术语是“weakly polynomial”,意思是“输入中位数的多项式,但仍取决于输入的数值。”

这是你需要在访谈中提到的吗?可能不是。分析算法并说运行时为O(log n)将运行时完美地描述为输入参数n的函数。更进一步,然后查看写出数字n需要多少位,然后提到运行时在输入的大小上是线性的,这是一个很好的繁荣,可能会让面试者感到高兴。

如果你没有提到这一点,如果一位面试官反对你,我真的很不高兴 - 如果你有良好的大学教育或做过很多自学,你就会知道这种事情。

答案 1 :(得分:1)

When you say that an algorithm takes O(N) time, and it's not specified what N is, then it's taken to be the size of the input.

In this case, however, the algorithm is said to to take O(n) time, where n identifies a specific input parameter. That is also perfectly OK, and is common when the size of the input isn't what you would practically want to measure against. You will also see complexity given in terms of multiple parameters, like O(|V|+|E]) for graph algorithms, etc.

To make things a bit more confusing, the input value n is a single machine word, and numbers that fit into 1 or 2 machine words are usually considered to be constant size, because in practice they are.

Since giving a complexity in terms of the size of n is therefore not useful in any way, if you were asked to give a complexity without any specific instructions of how to measure the input size, you would measure it in terms of the value of n, because that is the useful way to do it.