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 ...
随机推荐
- C#杀进程与之之子进程
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using S ...
- [wpf] collectionViewsource 排序 和分组
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase" xmlns:swd="clr-n ...
- LOCATE()和FIND_IN_SET()
locate(substr,str) 查找substr在str中第一次出现的位置,为空时返回0 SELECT login_name, LOCATE('ning',login_name) FROM us ...
- {经典}springmvc+mybatis+restful+webservice Jeesz分布式架构
框架简介--主要定位于互联网企业架构,已内置企业信息化系统的基础功能和高效的代码生成工具,包括:系统权限组件.数据权限组件.数据字典组件.核心工具 组件.视图操作组件.工作流组件组件.代码生成等.采用 ...
- php-fpm内存泄漏问题排查
生产环境内存泄漏问题排查,以下是排查思路 生产环境上有严重的内存溢出问题(红色框所示,正常值应为是 20M 左右)同时系统有 Core Dump 文件产生排查过程中还发现一个现象,如果关闭 OPc ...
- host.conf - 解析配置文件
DESCRIPTION (描述) 文件 /etc/host.conf 包含了为解析库声明的配置信息. 它应该每行含一个配置关键字, 其后跟着合适的配置信息. 系统识别的关键字有: order, tri ...
- (转) Weblogic在Linux上节点服务器启动正常,计算机连接不上
对于服务器AdminServer, 与计算机Machine-0相关联的节点管理器无法访问. 所有所选服务器当前都处于与此操作不兼容的状态, 或未与运行的节点管理器关联, 或 ...
- gitlab搭建之互备模式
gitlab搭建之互备模式 gitlab搭建之互备模式 前言:gitlab目前默认的部署方式是本地单机部署,为了提高gitlab环境的可靠性和稳定性,必须构建一套互备搭建方案:借助gitolilt ...
- Python 3标准库第三章
时间过得很快,又是一周过去了,今天感觉迷迷糊糊的,不在状态,然后,下面开始我们的讲解,还是跟大家分享一下我自己的一些想法,第一.怎么讲了,就是各位如果有怀才不遇的想法,我感觉最好不要有这种想法;第二. ...
- Keras class_weight和sample_weight用法
搬运: https://stackoverflow.com/questions/57610804/when-is-the-timing-to-use-sample-weights-in-keras i ...