循环运行到2供电n的时间复杂度是多少

时间:2019-02-02 16:48:32

标签: java time-complexity

循环运行到2为n供电的时间复杂度是多少? 请参考下面的代码段。

fn is_baz_get(foo_ref: Rc<RefCell<Foo>>) -> bool {
    match *foo_ref.borrow() {
        Foo::Bar(_) => false,
        Foo::Baz(_) => true
    }
}

1 个答案:

答案 0 :(得分:2)

如果数组中有n个元素,您将执行

2^0 = 1 computation in first loop
2^1 = 2 computation in second loop
2^2 = 4 computation in third loop
...
2^(n-1) = 2^(n-1) computation in n-th loop

总结所有这些 2^0 + 2^1 + 2^2 + ... + 2^(n-1) = 2^n-1来自几何级数和公式。所以您的时间复杂度为O(2^n)