Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何计算包含可能在任意点终止的内部循环的代码段的时间复杂度_Javascript_Time Complexity - Fatal编程技术网

Javascript 如何计算包含可能在任意点终止的内部循环的代码段的时间复杂度

Javascript 如何计算包含可能在任意点终止的内部循环的代码段的时间复杂度,javascript,time-complexity,Javascript,Time Complexity,如何计算以下代码段的时间复杂度 let count, barHeight, result = 1 << 31; for(let i = 0; i < heights.length; i++) { count = 1; barHeight = heights[i]; for(let j = i - 1; j >= 0; j--) { if (heights[j] >= barHeight) { count

如何计算以下代码段的时间复杂度

let count, barHeight, result = 1 << 31;
for(let i = 0; i < heights.length; i++) {
    count = 1;
    barHeight = heights[i];
    for(let j = i - 1; j >= 0; j--) {
        if (heights[j] >= barHeight) {
            count++;
        } else {
            break;
        }
    }

    for(let k = i+1; k< heights.length; k++) {
        if (heights[k] >= barHeight) {
            count++;
        } else {
            break;
        }
    }

    result = Math.max(result, count*barHeight);
}
let count,barHeight,result=1=0;j——){
如果(高度[j]>=杆高度){
计数++;
}否则{
打破
}
}
对于(设k=i+1;k=杆高度){
计数++;
}否则{
打破
}
}
结果=数学最大值(结果、计数*条形高度);
}
基本上,这个代码段是为了计算任何索引
i
,计算
heights
数组中有多少相邻索引不小于
heights[i]

在这种情况下,我有点困惑如何计算时间复杂度。 2个内回路可在任何点停止

谢谢

它是二次的
O(n^2)

在评估时间复杂度时,您应该始终关注最坏情况,除非有客观摊销证明最坏情况可以由所有其他情况摊销


这个算法是二次的。

Hi Huan,我的答案能解决你的问题吗?如果是的话,你能把它标记为接受吗?如果不行,你能告诉我为什么会这样吗?