901. 股票价格跨度
题解来自于:Lemon
type pair struct{
price int
span int
}
type StockSpanner struct {
stack []pair
}
func Constructor() StockSpanner {
return StockSpanner{[]pair{}}
}
func (this *StockSpanner) Next(price int) int {
// 跨度至少为1,就是自身,所以这里是1,如果要求是不包含自身,那么这里就是0
span := 1
// 栈不为空且栈顶元素的价格小于当前价格
for len(this.stack) > 0 && this.stack[len(this.stack)-1].price <= price {
span += this.stack[len(this.stack)-1].span // 累加小于当前price的span
this.stack = this.stack[:len(this.stack)-1] // pop栈顶
}
this.stack = append(this.stack, pair{price, span}) // 将当前的price和span加入
return span
}
// 不懂的话可以手动运算一下示例
只要把问题分析清楚了,代码写起来还是很简单的,核心的next方法内部使用的还是单调栈的思想。分析一下复杂度,时间复杂度还是O(n),n为调用next方法的次数,空间复杂度也是O(n)。