我在大O运行时计算Math.max吗



我很难理解天气或不使用Math.max。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

大O运行时是O(N(N+N((还是O(N(?

我假设在这种情况下,这并不重要,因为我们去掉常数,最后它将是O(N(N+N((=O(N但我只是想知道我是否应该将Math.max/Math.min作为一个循环,以供将来参考。

是的,如果将长度为nMath.max()的参数列表传递,则这是一个O(n(操作。Math.max()遍历每个参数。请参阅规范中的更多信息。

最新更新