[LeetCode] Min Stack

本文介绍了一种使用两个栈来高效实现带有获取最小元素操作的数据结构的方法。其中一个栈存储所有元素,另一个栈则记录遇到的最小元素。通过这种方式,在进行插入、删除操作时能够快速维护最小值。

The idea is to use two stacks.

For push, the first stack records the pushed elements and the second stack records all the minimum (including duplicates) that have been seen.

For pop, we need to compare with the top elements of the two stacks. If they are equal (the top element is also minimum, popping it out will change the minimum), pop both; otherwise, only pop the first stack.

The remaining top and getMin will be trivial: just return the top element of the first and second stack respectively.

The code is as follows.

 1 class MinStack {
 2 public:
 3     void push(int x) {
 4         if (stk1.empty() || x <= stk2.top())
 5             stk2.push(x);
 6         stk1.push(x);
 7     }
 8 
 9     void pop() {
10         if (stk1.top() == stk2.top())
11             stk2.pop();
12         stk1.pop();
13     }
14 
15     int top() {
16         return stk1.top();
17     }
18 
19     int getMin() {
20         return stk2.top();
21     }
22 private:
23     stack<int> stk1; 
24     stack<int> stk2;
25 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4557627.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值