algorithm - 分析算法的时间复杂度

标签 algorithm time-complexity

我写了一个合并两个链表的函数。 (请注意,该函数基于预先给定的代码,以防您想知道我为什么要调用函数 node(i))。

public SLL mergeUnsorted(SLL otherList)
{
    // find length of this list
    int length = 0 ;
    Iterator itr = this.iterator() ;
    while (itr.hasNext())
    {
        Object elem  = itr.next() ;
        length++ ;
    }

    // get each node from this list and
    // add it to front of otherList list
    int i = length -1 ;
    while (i >= 0)
    {
        // returns node from this list
        SLLNode ins = node(i) ;

        ins.succ = otherList.first ;
        otherList.first = ins ;
        i-- ;
    }
    return this ;
}

第一部分 O(n) 第二部分 O(n)

整体复杂度O(n)

还是 O(n^2) 因为我遍历列表两次?

最佳答案

遍历两次只是一个常量乘数。只要乘数不依赖于 n,它仍然是 O(n)。编辑:但是,请确保插入另一个列表是恒定时间的。如果执行此操作的时间与其他列表的大小成正比,那么,我想您可以看到会发生什么。

关于algorithm - 分析算法的时间复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5445389/

相关文章:

algorithm - Clog n的一个算法问题的设计[C++代码]

python - 如何访问python中矩阵每个元素的相邻单元格?

algorithm - 从 10^x 到 2^x 的大整数基数/基数转换

algorithm - 发现 n! 之间的区别!和一个 2^n 算法

java - 给定一组 n 个整数,返回总和为 0 的 k 个元素的所有子集

algorithm - 如何为回溯算法获得更严格的界限?

java - 是否有任何 'tricks' 可以加速非常大的背包组合类型 prob 的采样?

algorithm - 数据结构中的卫星信息是什么?

c++ - 在具有附加条件的图中找到最小加权路径

algorithm - 递归 Tribonacci 序列时间复杂度