编写一个 StockSpanner 类,它收集某些股票的每日报价,并返回该股票当日价格的跨度。
今天股票价格的跨度被定义为股票价格小于或等于今天价格的最大连续日数(从今天开始往回数,包括今天)。
例如,如果未来7天股票的价格是 [100, 80, 60, 70, 60, 75, 85],那么股票跨度将是 [1, 1, 1, 2, 1, 4, 6]。
示例:
输入:["StockSpanner","next","next","next","next","next","next","next"],
[[],[100],[80],[60],[70],[60],[75],[85]]
输出:[null,1,1,1,2,1,4,6]
解释:
首先,初始化 S = StockSpanner(),然后:
S.next(100) 被调用并返回 1,
S.next(80) 被调用并返回 1,
S.next(60) 被调用并返回 1,
S.next(70) 被调用并返回 2,
S.next(60) 被调用并返回 1,
S.next(75) 被调用并返回 4,
S.next(85) 被调用并返回 6。
注意 (例如) S.next(75) 返回 4,因为截至今天的最后 4 个价格
(包括今天的价格 75) 小于或等于今天的价格。
题解:
// 方法一:暴力法
var StockSpanner = function () {
this.stack = []
};
/**
* @param {number} price
* @return {number}
*/
StockSpanner.prototype.next = function (price) {
this.stack.push(price)
let res = 1
for (let i = this.stack.length - 1; i >= 0; i--) {
if (this.stack[this.stack.length - 1] >= this.stack[i - 1]) {
res++
} else {
break
}
}
return res
};
// 方法二:单调栈
var StockSpanner = function () {
this.stack = [];
this.count = 0;
};
/**
* @param {number} price
* @return {number}
*/
// 例子:[100, 80, 60, 70, 60, 75, 85]
// 第一轮:price => 100 tmp => 0 count => 1 res => 1
// stack => [{ index: 1, 100}]
// 第二轮:price => 80 tmp => 1 count => 2 res => 1
// stack => [{ index: 1, 100}, { index: 2, 80}]
// 第三轮:price => 60 tmp => 2 count => 3 res => 1
// stack => [{ index: 1, 100}, { index: 2, 80}, { index: 3, 60}]
// 第四轮:price => 70 tmp => 2 count => 4 res => 2
// stack => [{ index: 1, 100}, { index: 2, 80}, { index: 4, 70}]
// 第五轮:price => 60 tmp => 4 count => 5 res => 1
// stack => [{ index: 1, 100}, { index: 2, 80}, { index: 4, 70} { index: 5, 60}]
// 第六轮:price => 75 tmp => 2 count => 6 res => 4
// stack => [{ index: 1, 100}, { index: 2, 80}, { index: 6, 75}]
// 第七轮:price => 85 tmp => 1 count => 7 res => 6
// stack => [{ index: 1, 100}, { index: 7, 85}]
StockSpanner.prototype.next = function (price) {
// 维护单调递减栈
while (this.stack.length && price >= this.stack[this.stack.length - 1].value) {
this.stack.pop();
}
// tmp为当前栈顶的next数
let tmp = this.stack.length ? this.stack[this.stack.length - 1].index : 0;
// count记录next操作次数
this.count++;
this.stack.push({
index: this.count,
value: price
});
return this.count - tmp;
};
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。