博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode155——Min Stack
阅读量:3977 次
发布时间:2019-05-24

本文共 1136 字,大约阅读时间需要 3 分钟。

文章作者:Tyan

博客:  |   | 

1. 问题描述

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

push(x) – Push element x onto stack.

pop() – Removes the element on top of the stack.
top() – Get the top element.
getMin() – Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();minStack.push(-2);minStack.push(0);minStack.push(-3);minStack.getMin();   --> Returns -3.minStack.pop();minStack.top();      --> Returns 0.minStack.getMin();   --> Returns -2.

2. 求解

主要是模拟写一个最小栈。要注意push时可能会输入null。需要使用双栈实现,一个保存数据,一个保存最小值。由于随着数据出栈,最小值是不断变化的,因此需要一个最小值栈来保存最小值。

class MinStack {    private Stack
stack = new Stack<>(); private Stack
minStack = new Stack<>(); public void push(int x) { if(minStack.isEmpty() || x <= minStack.peek()) { minStack.push(x); } stack.push(x); } public void pop() { if(stack.peek().equals(minStack.peek())) { minStack.pop(); } stack.pop(); } public int top() { return stack.peek(); } public int getMin() { return minStack.peek(); }}

转载地址:http://pdwui.baihongyu.com/

你可能感兴趣的文章
onTouchEvent方法的使用
查看>>
Android详细解释键盘和鼠标事件
查看>>
如何成为强大的程序员?
查看>>
打包时sun.misc.ServiceConfigurationError
查看>>
摘自 管理自己[Managing Oneself]
查看>>
程序员开发大型应用程序的技巧
查看>>
远程团队管理的10条戒律
查看>>
在服务器上排除问题的头五分钟
查看>>
Diagnosing DFC Configuration Problems
查看>>
jboss java.lang.NoClassDefFoundError: Could not initialize class com.documentum.fc.client.DfClient
查看>>
芯片常见封装
查看>>
什么是oc门
查看>>
上拉电阻&nbsp;下拉电阻的汇总
查看>>
NTC热敏电阻的基本特性
查看>>
数字地和模拟地处理的基本原则
查看>>
集电极开路,漏极开路,推挽,上拉电…
查看>>
长尾式差分放大电路2
查看>>
十种精密整流电路
查看>>
红外线遥控原理
查看>>
放大电路的主要性能指标?
查看>>