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

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

题目描述:

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. 解法一: 用一个栈s和一个指示当前栈中最小值min_elem的int,在push操作或者pop操作中更新min_elem。
class MinStack {public:    /** initialize your data structure here. */    int min_elem;    stack
s; MinStack() { min_elem = INT_MIN; } void push(int x) { if (min_elem == INT_MIN) { min_elem = x; } else if (x < min_elem) { min_elem = x; } s.push(x); } void pop() { if (s.empty()) { return; } else { s.pop(); min_elem = INT_MIN; stack
temp_s; while (!s.empty()) { temp_s.push(s.top()); if (min_elem == INT_MIN) { min_elem = s.top(); } else if (s.top() < min_elem) { min_elem = s.top(); } s.pop(); } while (!temp_s.empty()) { s.push(temp_s.top()); temp_s.pop(); } } } int top() { return s.top(); } int getMin() { return min_elem; }};

 

这个解法不是很好的解法,虽然能够AC,但是效率在leetcode网站上的排名很低……

 

解法二:

使用两个栈,s和min。min记录当前栈中的一个递减序列,因为最小值的出栈操作仅和这个递减序列有关。

class MinStack {public:    /** initialize your data structure here. */    stack
s; stack
min; MinStack() { } void push(int x) { if (s.empty() || x <= getMin()) { min.push(x); } s.push(x); } void pop() { if (s.top() == min.top()) { min.pop(); } s.pop(); } int top() { return s.top(); } int getMin() { return min.top(); }};

这个版本是leetcode官方的版本,但是效率也不是最好的,但是真的非常简洁,再次印证了简洁即高效的代码准则。

 

 

 

 

 

转载于:https://www.cnblogs.com/maizi-1993/p/5937410.html

你可能感兴趣的文章
Azure Cosmos DB 使用费用参考
查看>>
【嵌入式开发】写入开发板Linux系统-模型S3C6410
查看>>
C# 子线程与主线程通讯方法一
查看>>
006——修改tomacat的编码
查看>>
《C程序设计语言》笔记 (八) UNIX系统接口
查看>>
git常用命令
查看>>
Android必知必会-获取视频文件的截图、缩略图
查看>>
(转)理解Bitblt、StretchBlt与SetDIBitsToDevice、StretchDibits
查看>>
python之路-基础篇-第七周
查看>>
高性能队列Disruptor系列2--浅析Disruptor
查看>>
ViurtualBox配置虚拟机Linux的网络环境
查看>>
VLC 媒体播放器
查看>>
勿忘国耻2018/09/18
查看>>
Jenkins部署码云SpringBoot项目
查看>>
多标签分类(multi-label classification)综述
查看>>
史上最全面的Spring-Boot-Cache使用与整合
查看>>
图的遍历(深度优先与广度优先搜索两种方案)
查看>>
快速读入模板
查看>>
把一张图片变成base64
查看>>
impdp报错: ORA-39064: 无法写入日志文件 ORA-29285: 文件写入错误
查看>>