【问题标题】:time-complexity of nested loop嵌套循环的时间复杂度
【发布时间】:2016-11-08 12:03:14
【问题描述】:

为什么是时间复杂度

function (n)
{
    //this loop executes n times

    for( i = 1 ; i <= n ; i + + )
    //this loop executes j times with j increase by the rate of i
    for( j = 1 ; j <= n ; j+ = i )
    print( “*” ) ;

}

它的运行时间是n*(n^1/2)=n^3/2

所以,O(n^3/2)

请用数学步骤解释。

提前谢谢你。

【问题讨论】:

    标签: data-structures time-complexity nested-loops


    【解决方案1】:

    运行时间O(n^{3/2}) 为界,但这并不紧迫!

    请注意,内部循环为每个i=1,2,...n 进行O(n/i) 迭代),因此时间复杂度为O(n * (1 + 1/2 + 1/3 + ... + 1/n)) = O(n log n)

    这是因为1+1/2+1/3+...+1/n=O(log n) 是众所周知的harmonic series

    【讨论】:

    • 对于 n=4....对于 i=1 ,内循环执行 5 次(j=1 到 4)对于 n=4...对于(i=2),它执行j=1,3...2 次,对于 (i=3),内循环为 j=1,4.. 再次执行两次.. 因为 j
    • 因为你是按i递增j,所以你最多进行K迭代,即内循环的迭代次数最大K其中@987654331 @。这是n/i 的边界形式。也就是说,当外部循环处于i-th 迭代中时,您最多在内部循环中进行ceil(n/i) 迭代。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2019-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多