Leetcode +155 Min Stack

编程入门 行业动态 更新时间:2024-10-27 09:33:15

<a href=https://www.elefans.com/category/jswz/34/1769930.html style=Leetcode +155 Min Stack"/>

Leetcode +155 Min Stack

Leetcode +155 Min Stack

题目描述

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路解析
class MinStack:def __init__(self):# 数据栈self.data = []# 辅助栈self.helper = []def push(self, x):self.data.append(x)if len(self.helper) == 0 or x <= self.helper[-1]:self.helper.append(x)else:self.helper.append(self.helper[-1])def pop(self):if self.data:self.helper.pop()return self.data.pop()def top(self):if self.data:return self.data[-1]def getMin(self):if self.helper:return self.helper[-1]# 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()

更多推荐

Leetcode +155 Min Stack

本文发布于:2023-07-28 15:43:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1239163.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Leetcode   Stack   Min

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!