Monotonic栈问题的时间复杂度
Time complexity of Monotonic stack question
据我了解,这段代码的时间复杂度是O(N)
for 循环只会迭代一次,所以时间复杂度为 O(N)
但是for循环里面有一个while循环
所以在for循环里面嵌套了一个while循环
为什么我们要忽略它的时间复杂度?
var dailyTemperatures = function(temperatures) {
let result = new Array(temperatures.length).fill(0);
let stack = [];
for(let i = 0; i < temperatures.length; i++) {
while(stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {
let index = stack.pop();
console.log('hello');
result[index] = i - index;
}
stack.push(i);
}
return result;
};
因为 while 循环只是简单地将堆栈元素一个接一个地弹出,并且堆栈中压入的元素不能超过 N 个(每个元素压入一次)。因此,即使while循环嵌套在for循环中,它也不会执行超过N次。
据我了解,这段代码的时间复杂度是O(N) for 循环只会迭代一次,所以时间复杂度为 O(N) 但是for循环里面有一个while循环
所以在for循环里面嵌套了一个while循环 为什么我们要忽略它的时间复杂度?
var dailyTemperatures = function(temperatures) {
let result = new Array(temperatures.length).fill(0);
let stack = [];
for(let i = 0; i < temperatures.length; i++) {
while(stack.length > 0 && temperatures[i] > temperatures[stack[stack.length - 1]]) {
let index = stack.pop();
console.log('hello');
result[index] = i - index;
}
stack.push(i);
}
return result;
};
因为 while 循环只是简单地将堆栈元素一个接一个地弹出,并且堆栈中压入的元素不能超过 N 个(每个元素压入一次)。因此,即使while循环嵌套在for循环中,它也不会执行超过N次。