leetcode-1381- Design a Stack With Increment Operation
问题
Design a stack which supports the following operations.
Implement the CustomStack
class:
CustomStack(int maxSize)
Initializes the object withmaxSize
which is the maximum number of elements in the stack or do nothing if the stack reached themaxSize
.void push(int x)
Addsx
to the top of the stack if the stack hasn’t reached themaxSize
.int pop()
Pops and returns the top of stack or -1 if the stack is empty.void inc(int k, int val)
Increments the bottomk
elements of the stack byval
. If there are less thank
elements in the stack, just increment all the elements in the stack.
Example 1:
1 | Input |
Constraints:
1 <= maxSize <= 1000
1 <= x <= 1000
1 <= k <= 1000
0 <= val <= 100
- At most
1000
calls will be made to each method ofincrement
,push
andpop
each separately.
分析
思路1: 使用一个普通的栈表示正常的push和pop,使用一个树状数组来表示区间的增长。push时正常push。pop时加上树状数组上的延迟标记,并对延迟标记进行调整。时间复杂度push: O(1), pop() : O(logn), increment: O(logn).
思路2: 分析可知increment进行区间增常时,区间头总是0。因此可以另外使用一个inc数组进行延迟标记的,inc[i] 表示栈中前i个元素都应该加1。push时正常push。pop时加上inc[i],并令inc[i-1] = inc[i]. increment 时对inc[i]进行负值。push: O(1), pop() : O(1), increment: O(1)
。参考)
代码1
1 | // push: O(1), pop() : O(logn), increment: O(logn) |
代码2
1 | class CustomStack { |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/15/leetcode-1381/
License: 知识共享署名-非商业性使用 4.0 国际许可协议