Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack
class:
MinStack()
initializes the stack object.void push(int val)
pushes the element val onto the stack.void pop()
removes the element on the top of the stack.int top()
gets the top element of the stack.int getMin()
retrieves the minimum element in the stack.Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
设计具有 push, pop, top 操作,并能在常数时间 O(n) 内查询到最小元素的堆叠
min_stack
纪录堆叠最小值stack
list 作为堆叠纪录stack[-1]
min_stack[-1]
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, val: int) -> None:
self.stack.append(val)
if not self.min_stack or val <= self.min_stack[-1]:
self.min_stack.append(val)
def pop(self) -> None:
if self.stack.pop() == self.min_stack[-1]:
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
<<: 网页编排Grid-30天学会HTML+CSS,制作精美网站
>>: JavaScript Day 30. 关於 JavaScript 中的 This
今天的文章分为两部分,一个是今天做完的部分修改,一部份是参赛感想 今日的品质更新 & 逻辑修...
WebSocket 前端对於WebSocket这项技术应该不陌生,以往会需要使用轮询的方式更新资料,...
前言 接下来要介绍的东西并不是学什麽工具, 而是怎麽把我们已经会的程序语言写得更有系统, 来达到高效...
VPC介绍 介绍完关於GCP使用这权限设置,再来需要了解的是GCP中的网路层,在网路部分可以说是极其...
前言 各位早安,书接上回我们练习了一些基础list用法跟一些技巧,今天我们要来深入探讨list更多能...