【问题标题】:Finding the Space Complexitiy for these methods查找这些方法的空间复杂度
【发布时间】:2015-10-03 03:23:36
【问题描述】:

我熟悉以下两种方法的运行时间,即 O(N)。但是,我不熟悉空间复杂度。由于这些方法仅由赋值语句、比较语句和循环组成,因此我假设空间复杂度仅为 O(1),但想确定一下。谢谢你。

//first method 
public static <E> Node<E> buildList(E[] items) {
    Node<E> head = null; 
    if (items!=null && items.length>0) {
        head = new Node<E> (items[0], null);
        Node<E> tail = head;
        for (int i=1; i<items.length; i++) {
            tail.next = new Node<E>(items[i], null);
            tail = tail.next;
        }
    }
    return head;
}

//second method
public static <E> int getLength(Node<E> head) {
    int length = 0; 
    Node<E> node = head;
    while (node!=null) {
        length++;
        node = node.next; 
    }
    return length;
}

【问题讨论】:

    标签: performance


    【解决方案1】:

    如this post 中所述,空间复杂度与算法使用的内存量有关,具体取决于输入的大小。

    例如,具有O(1) 空间复杂度的算法使用固定数量的内存,与输入大小无关。这是您的第二种算法的情况,它基本上只使用了一些额外的变量。

    具有O(n) 空间复杂度的算法使用与其输入大小成正比的内存量。这是您的第一个算法为输入的每个元素执行一次分配(一个new)的情况。

    【讨论】:

    • 太棒了。谢谢!我较早发现了该帖子并且非常有帮助,但我想确定一下。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2016-09-28
    • 1970-01-01
    • 2020-07-24
    • 2019-10-08
    • 2011-02-16
    • 2020-04-02
    相关资源
    最近更新 更多