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 ...
随机推荐
- 01Spring基于xml的IOC配置--入门
01Spring基于xml的IOC配置 1.创建一个普通的maven工程 1.1 选择maven,不用骨架,点击下一步. 1.2 填写GroupId.ArtifactId.Version.填完点击下一 ...
- 用ajax写机器人聊天的案例
HTML 中的文档 <body> <h3>简单的Ajax实例</h3> <div class="chatbox"> <!-- ...
- keymaps - 对键盘映射文件的描述
描述 (DESCRIPTION) loadkeys(1) 能够 通过 调入 指定的 文件 修改 键盘翻译表, 键盘翻译表 通常 用于 内核的 键盘驱动程序; 另外 dumpkeys(1) 可以 根据 ...
- 使用 gitolite 管理配置 git 库的权限
问题:每次创建git库都需要在gitolite的配置文件中添加git库的配置信息,为了方便管理git库,不在重复提交,所以修改gitolite的配置管理文件. 环境:ubuntu16.04 安装git ...
- 我来说说XML文件中的xmlns、xmlns:xsi和xsi:schemaLocation、dtd文件的具体含义
文章摘自:https://yq.aliyun.com/articles/40353 http://www.cnblogs.com/zhao1949/p/5652167.ht ...
- Kong组件构成及使用
Service: Service 顾名思义,就是我们自己定义的上游服务,通过Kong匹配到相应的请求要转发的地方 Service 可以与下面的Route进行关联,一个Service可以有很多Route ...
- Spring Boot JPA - Querydsl
https://lufficc.com/blog/spring-boot-jpa-querydsl
- Metafile::EmfToWmfBits的使用
其中涉及到string转换LPCWSTR以及模块绝对路径的调用 #include <iostream> #include <stdio.h> #include <WIND ...
- python中导入from appium import webdriver时报错:ModuleNotFoundError: No module named 'appium'
1.检查一下有没有安装Appium-Python-Client,执行语句:pip install Appium-Python-Client进行安装 2.安装后,出现ModuleNotFoundErro ...
- 提高Linux操作系统性能
提高Linux操作系统性能 2011-01-05 13:48 佚名 字号:T | T 本文从磁盘,文件及文件系统,内存和编译等方面详细的讲述了如何对Linux系统性能进行调谐.不管是Linux服务器还 ...