Skip to content

1381.设计一个支持增量操作的栈

虽然 leetcode 中显示该难度为中等,但实际做起来的话应该算是简单难度的题目。

ts
class CustomStack {
  stack: number[] = []
  maxSize: number

  constructor(maxSize: number) {
    this.maxSize = maxSize
  }

  push(x: number): void {
    if (this.stack.length >= this.maxSize) return
    this.stack.push(x)
  }

  pop(): number {
    if (this.stack.length > 0) {
      return this.stack.pop()
    } else {
      return -1
    }
  }

  increment(k: number, val: number): void {
    const min = Math.min(k, this.stack.length)
    for (let i = 0; i < min; i++) {
      this.stack[i] += val
    }
  }
}