剑指offer20:定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。...

1 题目描述

  定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

2. 思路和方法

  利用辅助栈来存储现有栈的最小值。在入栈和出栈的时候将现有栈和最小值栈进行比较。入栈时,若新值比最小值栈的栈顶还小,则将该值同时push到最小值栈;出栈时,若现有栈的栈顶和最小值栈栈顶一致,则同时出栈,否则,仅仅现有栈pop;通过这一操作,最小值栈的栈顶将永远是现有栈元素中的最下值。

3 C++核心代码

 1 class Solution {
 2 public:
 3     stack<int> my_stack, min_stack;
 4     void push(int value) {
 5         my_stack.push(value);
 6         if (min_stack.size() == 0)
 7             min_stack.push(value);
 8         if (value < min_stack.top())
 9             min_stack.push(value);
10     }
11     void pop() {
12         if (my_stack.top() == min_stack.top())
13         {
14             my_stack.pop();
15             min_stack.pop();
16         }
17         else
18             my_stack.pop();
19     }
20     int top() {
21         return my_stack.top();
22     }
23     int min() {
24         return min_stack.top();
25     }
26 };
View Code

4 C++完整代码

 1 #include<iostream>
 2 #include<stack>
 3 
 4 using namespace std;
 5 
 6 
 7 template<class T>
 8 class StackWithMin
 9 {
10 public:
11     StackWithMin(){}
12     void push(T data)
13     {
14         s.push(data);
15         if (minStack.empty() || data <= minStack.top())
16             minStack.push(data);
17     }
18     void pop()
19     {
20         if (s.top() == minStack.top())
21             minStack.pop();
22         s.pop();
23     }
24     T& minData()
25     {
26         if (!minStack.empty())
27             return minStack.top();
28     }
29 
30 private:
31     stack<T> s;
32     stack<T> minStack;
33 };
34 
35 void Test()
36 {
37     StackWithMin<int> min_stack;
38     min_stack.push(5);
39     min_stack.push(2);
40     min_stack.push(3);
41     min_stack.push(4);
42     cout << min_stack.minData() << endl;
43 }
44 
45 
46 int main()
47 {
48     Test();
49 
50     system("pause");
51     return 0;
52 }
View Code

参考资料

https://blog.csdn.net/u011261670/article/details/81008032

https://blog.csdn.net/zy20150613/article/details/89928236

https://blog.csdn.net/wenqiang1208/article/details/75335141

转载于:https://www.cnblogs.com/wxwhnu/p/11410213.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值