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 ...
随机推荐
- liunx 环境下安装 Eclipse C++
第一步:首先安装JDK 进入JDK官网:https://www.oracle.com/technetwork/java/javase/downloads/index.html 下载对应的jdk 注意 ...
- Linux中如何添加/删除FTP用户并设置权限
在linux中添加ftp用户,并设置相应的权限,操作步骤如下: 1.环境:ftp为vsftp.被设置用户名为test.被限制路径为/home/test 2.创建建用户:在root用户下: user ...
- Go基础学习
Go基础学习 go的基础语法 fmt.Println("hello world!") //go采用行分隔符 关键字 下面列举了 Go 代码中会使用到的 25 个关键字或保留字: b ...
- paramiko模块(基于SSH用于连接远程服务器)
paramiko模块,基于SSH用于连接远程服务器并执行相关操作 class SSHConnection(object): def __init__(self, host_dict): self.ho ...
- python实现建造者模式
python实现建造者模式 前言 无论是在现实世界中还是在软件系统中,都存在一些复杂的对象,它们拥有多个组成部分,如汽车,它包括车轮.方向盘.发送机等各种部件.而对于大多数用户而言,无须知道这些部件的 ...
- HashMap 的实现原理(1.8)
详见:https://blog.csdn.net/richard_jason/article/details/53887222 HashMap概述 1.初始容量默认为16 最大为2的30次方,负载因子 ...
- Big Data(八)MapReduce的搭建和初步使用
---恢复内容开始--- 回顾: 1.最终开发MR的计算程序 2.hadoop 2.x 出现了一个yarn:资源管理>>MR没有后台场服务 yarn模型:container 容器,里面会运 ...
- 【react学习一】首先先create-react-app 配置less、sass
1.安装初始化 npm create-react-app react-demo 2.安装初始化 npm run eject 3.配置sass / less cnpm i sass-loader nod ...
- oracle基本语句(第七章、数据库逻辑对象管理)
索引.实体化视图.簇.散列簇.序列.同义词 1.创建表 CREATE TABLE <表名>(<列名1> <数据类型>,……); CREATE GLOBAL TEMP ...
- hdu 6377 : 度度熊看球赛
题目链接 题解: 将原问题转换为 对于全部 (2n)! 种情况,每种情况对ans的贡献为 D^k,其中k表示该情况下有k对情侣座位相邻. 预处理好共有 i (1<=i<=N)对情侣时,出现 ...