博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
min stack
阅读量:4638 次
发布时间:2019-06-09

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

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

Example

push(1)pop()   // return 1push(2)push(3)min()   // return 2push(1)min()   // return 1
Note

min operation will never be called if there is no number in the stack.

 

思路是新建一个堆栈用来存储最小值min,每次往stack里push值的时候,如果push的值比min里保存的值小,就把新的值同时push进min里。

在pop的时候要考虑,如果要pop的值刚好是最小值,就要同时把min里的最小值pop掉。

 

java里stack的值保存不同类型,直接用==来判断会出错,需要用equals来判断是否相同。

 

 

public class MinStack {        Stack
stk=new Stack
(); Stack
min=new Stack
(); public MinStack() { // do initialize if necessary } public void push(int number) { // write your code here if(min.empty()||number<=min.peek()) { min.push(number); } stk.push(number); } public int pop() { // write your code here if(stk.peek().equals(min.peek())) { min.pop(); } return stk.pop(); } public int min() { // write your code here return min.peek(); }}

 

转载于:https://www.cnblogs.com/kittyamin/p/5115388.html

你可能感兴趣的文章
[NOI2005]聪聪与可可(期望dp)
查看>>
POJ 3723
查看>>
Maven的安装
查看>>
angular初步认识一
查看>>
springmvc3.2+spring+hibernate4全注解方式整合(一)
查看>>
Elgg网站迁移指南
查看>>
素数筛法优化
查看>>
installshield 注册dll
查看>>
Sublime Text 3 及Package Control 安装(附上一个3103可用的Key)
查看>>
LTE QCI分类 QoS
查看>>
Get MAC address using POSIX APIs
查看>>
bzoj2120
查看>>
基于uFUN开发板的心率计(一)DMA方式获取传感器数据
查看>>
【dp】船
查看>>
oracle, group by, having, where
查看>>
⑥python模块初识、pyc和PyCodeObject
查看>>
object-c中管理文件和目录:NSFileManager使用方法
查看>>
Kibana:分析及可视化日志文件
查看>>
nodejs pm2使用
查看>>
cocos2d-x 3.10 PageView BUG
查看>>