【发布时间】:2021-09-05 17:28:32
【问题描述】:
我无法理解天气或不使用 Math.max 应该算作一个循环,因此应该包含在计算 Big O 运行时间中。
我假设 Math.max 找到它必须循环的最大值并比较它提供的所有值。因此它实际上是循环的。
我在 JS 中的代码:
function getWaterCapacityPerSurface(surface){
let waterAmount = 0;
// full loop
for(let i = 1; i < surface.length - 1; i++){
const current = surface[i];
// I assume each slice is counted as a half of the full loop
const leftSlice = surface.slice(0, (i - 1 < 0 ? 0 : i));
const rightSlice = surface.slice(i + 1, surface.length);
// I assume each Math.max is counted as a half of the full loop
const leftBound = Math.max(...leftSlice);
const rightBound = Math.max(...rightSlice);
const canWaterStay = leftBound > current && rightBound > current;
const currentBound = Math.min(leftBound, rightBound);
const waterLevel = currentBound - current;
if(canWaterStay) waterAmount += waterLevel;
}
return waterAmount;
}
console.log(getWaterCapacityPerSurface([4,2,1,3,0,1,2]));
// returns 6
Big O 运行时间是 O(N(N+N)) 还是 O(N(N))?
我假设在这种情况下它并不重要,因为我们删除了常量,最后它将是 O(N(N+N)) = O(N(2N)) = O(N(N )) = O(N²) 但我只是想知道天气,我应该将 Math.max/Math.min 算作循环以供将来参考。
【问题讨论】: