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. Hibernate 初体验

    为什么会产生 Hibernate Mybatis 这类的dao层框架 传统的jdbc 虽然执行速度很快,但是开发效率很低,随着面向对象开发的设计思想,在面向对象编程中 将对象 进行持久化,存入关系型的 ...

  2. CentOS6.6安装使用MyCat

    https://blog.csdn.net/u012948302/article/details/78902092 1. 安装Java环境MyCAT 是使用 JAVA 语言进行编写开发,使用前需要先安 ...

  3. 浅谈XXE

    转自FReeBUF 0×00. 介绍 现在越来越多主要的web程序被发现和报告存在XXE(XML External Entity attack)漏洞,比如说facebook.paypal等等. 举个例 ...

  4. 为Xcode配置Git和Github

    Xcode.Git和Github是三个伟大的编程工具.本文记录一下如何在Xcode中使用Git作为源代码控制工具,以及如何将本地的Git仓库和远程Github上的仓库集成起来. 1. 如何为新建的Xc ...

  5. Malloc与Free不调用构造函数与析构函数

    例子: #include "stdafx.h" #include <new> #include <iostream> using namespace std ...

  6. Vue Cli 移动端开发

    一.

  7. Jmeter线程组间传递参数

    现在做测试和以前不太一样了,以前只要站在一个用户的角度做端到端的UI测试就可以了,现在不会做接口测试,出去都不好意思和别人打招呼.那提到接口测试,就不得不提一下接口测试利器Jmeter,大家也都知道, ...

  8. scp 远程文件复制命令

    scp 远程文件复制工具 1.命令功能 scp用户在不同linux主机间复制文件,他采用ssh协议保障复制的安全性.scp复制是全量完整复制,效率不高,使用与第一次复制,增量复制建议rsync命令. ...

  9. P1086 花生采摘题解

    这道题只是普通的模拟,不是贪心! 重点在于这句话:“然后再找出剩下的植株里花生最多的,去采摘它的花生”. 也就是,你下一个必须找到剩下花生最多的,而不是按照贪心思想来考虑在限定时间内的最优解 那么,应 ...

  10. RabbitMQ 启用页面管理功能并设置权限

    RabbitMQ 启用页面管理功能并设置权限 RabbitMQ guest administrator  在安装完 rabbitmq 后,默认有一个 guest/guest 账号密码,但是为了安全,此 ...