LeetCode 1381. Design a Stack With Increment Operation
Question
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.
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.
Solution
inc操作是这个题的重点,如果采取常用的栈操作,需要弹出再放入,降低其时间复杂度。
- Solution1: 在比赛中,我看见如上的参数限制,所以我想到使用基于数组的栈,这样在进行inc,只需要从头开始加。
- Solution2: 参考了Lee215大佬的解法后发现,思路更加妙。依然采取栈,但是需要一个数组来记录每次加的数,并且放在最高位,每次需要pop的时候, 就依次往前面计算。真的很妙!
Code
1 | // time:O(n) space:O(n) |