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的更多相关文章

  1. [LeetCode] Min Stack 最小栈

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

  2. 【leetcode】Min Stack -- python版

    题目描述: Design a stack that supports push, pop, top, and retrieving the minimum element in constant ti ...

  3. 【leetcode】Min Stack(easy)

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

  4. [LeetCode] Min Stack

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

  5. Java for LeetCode 155 Min Stack

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

  6. LeetCode之Min Stack 实现最小栈

    LeetCode相关的网上资源比较多,看到题目一定要自己做一遍,然后去学习参考其他的解法. 链接: https://oj.leetcode.com/problems/min-stack/ 题目描述: ...

  7. leetcode 155. Min Stack --------- java

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

  8. Min Stack [LeetCode 155]

    1- 问题描述 Design a stack that supports push, pop, top, and retrieving the minimum element in constant ...

  9. Min Stack

    Min Stack Design a stack that supports push, pop, top, and retrieving the minimum element in constan ...

随机推荐

  1. maven配置生成可执行的jar:maven-shade-plugin

    默认打包生成的jar是不能直接运行的,因为带有main方法的信息不会添加到mainifest中,需要借助maven-shade-plugin <project> ... <build ...

  2. [.net core]2.hello word(.net core web app模版简介)

    创建一个.net core web app project 弹出这个窗口 empty代表 最低依赖,  意味着往往需要手动按需添加依赖. web应用程序(模型视力控制器) 则会帮你创建好control ...

  3. 19.AutoMapper 之开放式泛型(Open Generics)

    https://www.jianshu.com/p/ce4c7e291408 开放式泛型(Open Generics) AutoMapper可以支持开放式泛型的映射.为开放式泛型创建映射: publi ...

  4. ActiveMQ利用ajax收发消息

    准备工作: 后台需要导包: activemq-all.jar activemq-web.jar jetty-all.jar 如果是maven项目: pom.xml <dependency> ...

  5. HTTP常用状态码详解

    HTTP状态码: HTTP定义遵循一条规则:所有状态码的第一个数字代表了响应的状态.1表示消息:2表示成功:3表示重定向:4表示请求错误:5.6表示服务器错误.如下图: 1xx: 这一类型的状态码,代 ...

  6. 【leetcode 136】136. Single Number

    要求:给定一个整数数组,除了其中1个元素之外,其他元素都会出现两次.找出这个只出现1次的元素. 例: array =[3,3,2,2,1]    找出元素1. 思路:最开始的想法是用两次for循环,拿 ...

  7. pyinstaller打包总结

    建立py打包文件 if __name__ == '__main__': from PyInstaller.__main__ import run #opts=['music.py','--path=C ...

  8. 三、Vue CLI-单页面

    一.单页面 代码如下: <template> <div class="header">{{title}}</div> </template ...

  9. framebuffer测试程序

    /* framebuffer简单测试程序 网上转载 很多次 的程序 :-) */ #include <stdio.h> #include <stdlib.h> #include ...

  10. Big Data(三)伪分布式和完全分布式的搭建

    关于伪分布式的配置全程 伪分布式图示 1.安装VMWare WorkStation,直接下一步,输入激活码即可安装 2.安装Linux(需要100GB) 引导分区Boot200MB 交换分区Swap2 ...