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. leetcode 75. Sort Colors (荷兰三色旗问题)

    Given an array with n objects colored red, white or blue, sort them in-place so that objects of the ...

  2. 利用bing图片搜索接口开发图片搜索应用程序

    概述:通过bing的图片搜索引擎,开发自己的图片搜索应用程序.bing的图片搜索接口是收费的,但是初次注册使用,key可以免费试用30天 程序运行效果如下 一,代码如下 static SearchRe ...

  3. G1 垃圾收集器之对象分配过程

    G1的年轻代由eden region 和 survivor region 两部分组成,新建的对象(除了巨型对象)大部分都在eden region中分配内存,如果分配失败,说明eden region已经 ...

  4. P多行溢出省略号的处理

    因为-webkit-line-clamp: 2不兼容火狐或IE,采用判断浏览器的方式来启用哪个方式 先判断是什么浏览器 //判断是否是谷歌浏览器 if (!stripos($_SERVER[" ...

  5. 如何写一个 Burp 插件

    Burp 是 Web 安全测试中不可或缺的神器.每一个师傅的电脑里面应该都有一个 Burp.同时 Burp 和很多其他神器一样,它也支持插件.但是目前总体来说网上 Burp 插件开发的资料不是特别特别 ...

  6. python 四舍五入进位不准

    python中四舍五入进位不准,自己写了个方法结果: def new_round(_float, _len): ''' 四舍五入保留小数位,如果想实现 0.2 显示为 0.20,可使用 '%.2f' ...

  7. ——HTTP状态码

    200 请求成功,请求所希望的响应头或数据体将随此返回 302 请求的资源现在临时从不同的URI响应请求,由于这样的重定向是临时的,客户端应当继续向原有地址发送以后的请求. 304 如果客户端发送了一 ...

  8. python常见问题解决方案

    平时工作中经常需要用到这些python小技巧,顺便做个记录 import requests import time def get_pr(domain): pr = 6 time.sleep(1) h ...

  9. softmax+交叉熵

    1 softmax函数 softmax函数的定义为 $$softmax(x)=\frac{e^{x_i}}{\sum_j e^{x_j}} \tag{1}$$ softmax函数的特点有 函数值在[0 ...

  10. juniper 命令

    show chassis hardware 查看系统硬件配置,fpc表示板卡,pic表示板卡中的槽位,xcvr表示板卡中的槽位的端口位置 show chassis envirmonent 查看系统运行 ...