41. 包含min函数的栈
函数 包含 41 min
2023-09-27 14:27:32 时间
Powered by:NEFU AB-IN
文章目录
41. 包含min函数的栈
-
题意
设计一个支持push,pop,top等操作并且可以在O(1)时间内检索出最小元素的堆栈。
push(x)–将元素x插入栈中
pop()–移除栈顶元素
top()–得到栈顶元素
getMin()–得到栈中最小元素 -
思路
创建两个栈
- a栈代表原栈
- b栈代表最小元素栈,即第i个元素存的是a栈前i个元素的最小值
所以b的每个新元素,就从a的新元素和b的栈顶中,取最小值即可
-
代码
class MinStack(object): def __init__(self): self.a = [] self.b = [] """ initialize your data structure here. """ def push(self, x): self.a.append(x) if not self.b: self.b.append(x) else: self.b.append(min(self.b[-1], x)) """ :type x: int :rtype: void """ def pop(self): self.a.pop() self.b.pop() """ :rtype: void """ def top(self): return self.a[-1] """ :rtype: int """ def getMin(self): return self.b[-1] """ :rtype: int """ # Your MinStack object will be instantiated and called as such: # obj = MinStack() # obj.push(x) # obj.pop() # param_3 = obj.top() # param_4 = obj.getMin()
相关文章
- Displaced ReLU激活函数
- delphi:函数大全 1(StrUtils.pas)(转载)
- Python常用函数:splitlines()【按照行(‘r‘, ‘rn‘, n‘)分隔,返回一个包含各行作为元素的列表】
- 包含 min 函数的栈
- 通用函数之时间转换
- C++之虚函数
- 多重继承的构造函数和析构函数的执行顺序(包含虚基类)
- TypeScript学习(二)函数重载
- js 函数节流和防抖
- oracle 10g函数大全--分析函数
- Python numpy.core.records.fromstring函数方法的使用
- Python numpy.ones_like函数方法的使用
- C++常函数
- c语言字符串分割函数(转)
- MFC中消息循环处理的几个函数之间的区别
- C++函数的哑元参数
- C++程序设计函数部分(定义+实例)
- 向函数中传递指针和传递指针的引用的区别