Design a stack that supports getMin() in O(1) time and O(1) extra space
Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.
Example:
Consider the following SpecialStack
16 --> TOP
15
29
19
18
When getMin() is called it should return 15,
which is the minimum element in the current stack.
If we do pop two times on stack, the stack becomes
29 --> TOP
19
18
When getMin() is called, it should return 18
which is the minimum in the current stack.
- 解答
# Class to make a Node
class Node:
# Constructor which assign argument to nade's value
def __init__(self, value):
self.value = value
self.next = None
# This method returns the string representation of the object.
def __str__(self):
return "Node({})".format(self.value)
# __repr__ is same as __str__
__repr__ = __str__
class Stack:
# Stack Constructor initialise top of stack and counter.
def __init__(self):
self.top = None
self.count = 0
self.minimum = None
# This method returns the string representation of the object (stack).
def __str__(self):
temp = self.top
out = []
while temp:
out.append(str(temp.value))
temp = temp.next
out = '\n'.join(out)
return ('Top {} \n\nStack :\n{}'.format(self.top,out))
# __repr__ is same as __str__
__repr__=__str__
# This method is used to get minimum element of stack
def getMin(self):
if self.top is None:
return "Stack is empty"
else:
print("Minimum Element in the stack is: {}" .format(self.minimum))
# Method to check if Stack is Empty or not
def isEmpty(self):
# If top equals to None then stack is empty
if self.top == None:
return True
else:
# If top not equal to None then stack is empty
return False
# This method returns length of stack
def __len__(self):
self.count = 0
tempNode = self.top
while tempNode:
tempNode = tempNode.next
self.count+=1
return self.count
# This method returns top of stack
def peek(self):
if self.top is None:
print ("Stack is empty")
else:
if self.top.value < self.minimum:
print("Top Most Element is: {}" .format(self.minimum))
else:
print("Top Most Element is: {}" .format(self.top.value))
# This method is used to add node to stack
def push(self,value):
if self.top is None:
self.top = Node(value)
self.minimum = value
elif value < self.minimum:
temp = (2 * value) - self.minimum
new_node = Node(temp)
new_node.next = self.top
self.top = new_node
self.minimum = value
else:
new_node = Node(value)
new_node.next = self.top
self.top = new_node
print("Number Inserted: {}" .format(value))
# This method is used to pop top of stack
def pop(self):
if self.top is None:
print( "Stack is empty")
else:
removedNode = self.top.value
self.top = self.top.next
if removedNode < self.minimum:
print ("Top Most Element Removed :{} " .format(self.minimum))
self.minimum = ( ( 2 * self.minimum ) - removedNode )
else:
print ("Top Most Element Removed : {}" .format(removedNode))
# Driver program to test above class
stack = Stack()
stack.push(3)
stack.push(5)
stack.getMin()
stack.push(2)
stack.push(1)
stack.getMin()
stack.pop()
stack.getMin()
stack.pop()
stack.peek()
# This code is contributed by Blinkii
- 分析
https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/
Design a stack that supports getMin() in O(1) time and O(1) extra space的更多相关文章
- [LeetCode] Min Stack 最小栈
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- 【leetcode】Min Stack -- python版
题目描述: Design a stack that supports push, pop, top, and retrieving the minimum element in constant ti ...
- 【leetcode】Min Stack(easy)
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- [LeetCode] Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- Java for LeetCode 155 Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- LeetCode之Min Stack 实现最小栈
LeetCode相关的网上资源比较多,看到题目一定要自己做一遍,然后去学习参考其他的解法. 链接: https://oj.leetcode.com/problems/min-stack/ 题目描述: ...
- leetcode 155. Min Stack --------- java
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...
- Min Stack [LeetCode 155]
1- 问题描述 Design a stack that supports push, pop, top, and retrieving the minimum element in constant ...
- Min Stack
Min Stack Design a stack that supports push, pop, top, and retrieving the minimum element in constan ...
随机推荐
- Jade学习(四)之结合node如何编译执行
1.首先安装node 2.新建一个文件夹并进入该文件夹 3.安装jade 4.在新建的文件夹下新建js文件,写nodejs代码 5.在vscode中利用插件code runner直接执行js文件,输出 ...
- luogu P1587 [NOI2016]循环之美
传送门 首先要知道什么样的数才是"纯循环数".打表可以发现,这样的数当且仅当分母和\(k\)互质,这是因为,首先考虑除法过程,每次先给当前余数\(*k\),然后对分母做带余除法,那 ...
- ios / % 四舍五入 向上取整(ceil()) 向下取整(floor())
1. / //Test "/" cout << "Test \"/\"!" << endl; cout ...
- VMware 中的win7虚拟机在一段时间后就会自动挂起
VMware workstation 中的win7虚拟机在一段时间不用后就会自动挂起. 其实这不是VMware workstation 的问题,而是win7的问题.关闭win7系统 的自动休眠功能即可 ...
- python-装饰器2
python-装饰器2 1.函数既“变量 def bar(): print("in the bar") def foo(): print("in the foo" ...
- (转) Delete/Truncate删除,释放表空间、降低高水位线、resize释放磁盘空间相关优化
硬盘空间不足,打算删除数据库中的多余数据,但删除数据后,硬盘硬盘空间不能释放.[delete后用:alter table table_name move truncate后用:alter tab ...
- css画心形、三角形的总结
.heart { width: 10px; height: 10px; /* position: fixed; */ background: #fff; transform: rotate(45deg ...
- SpringMVC初识
1 SpringMVC的概述 Spring为展现层提供的基于MVC设计理念的优秀的web框架,是目前最主流的MVC框架之一. Spring3.0后面全面超过Struts2,成为了最优秀的MVC框架. ...
- k-means伪代码
1.初始化k个簇中心. 2.更新所有样本点簇归属:样本点到哪个簇中心点最近就属于哪个簇. 3.重新计算每个簇的中心点(直到簇中心点不再变化或达到更新最大次数) #k-means伪代码 import n ...
- CodeForces-721A-One-dimensional Japanese Crossword
链接: https://vjudge.net/problem/CodeForces-721A 题意: Recently Adaltik discovered japanese crosswords. ...