title Link:https://oj.leetcode.com/problems/min-stack/
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.
Analysis: The topic requires the design of a stack to perform push,pop,top in a constant time and to get the minimum value of min operation.
algorithm One: establish a struct, where one domain value is x and the other field value is the minimum value in the stack. Therefore, the minimum value of the entire stack can be obtained within the time of O (1). But the result of this algorithm is: Memory limit exceed.
algorithm Two: build another stack s2, the top element of the stack is S1 the minimum value of all current elements.
Algorithm One code:
#include <iostream> #include <stack>using namespace std;class minstack{private:typedef struct Node {int val; int min_temp; }tnode; Stack<tnode> s; public:void push (int x) {tnode n; N.val = x; if (S.empty ()) {n.min_temp = x; } else {if (X < S.top (). min_temp) {N.min_temp = x; } else {n.min_temp = S.top (). min_temp; }} s.push (n); } void Pop () {s.pop (); } int Top () {return S.top (). Val; } int Getmin () {return s.top (). min_temp; }};int Main () {Minstack ms;ms.push (1); Ms.push (2); Ms.push (3); Ms.push (4); Ms.push (5);cout<< "top =" << Ms.top () << "min =" <<ms.getmin () <<endl;ms.pop ();cout<< "top =" <<ms.top () << "min =" << Ms.getmin () <<endl;ms.pop ();cout<< "top =" <<ms.top () << "min =" <<ms.getmin () << Endl;ms.pop ();cout<< "top =" <<ms.top () << "min =" <<ms.getmin () <<endl;ms.pop (); cout << "top =" <<ms.top () << "min =" <<ms.getmin () <<endl;ms.pop (); System ("pause"); return 0;} <strong></strong>
The result: memory limit exceed. The reason is because the min_temp domain takes up too much space, because each element will have a minimum value, which is completely unnecessary.
ac+ complete code for algorithm two:
#include <iostream> #include <stack>using namespace Std;class minstack{private:stack<int> s1;stack <int> s2;public:void push (int x) {s1.push (x); if (S2.empty ()) {S2.push (x);} else if (x <= s2.top ()) {S2.push (x);}} void Pop () {int top = S1.top (); S1.pop (); if (Top<=s2.top ()) {S2.pop ();}} int Top () {return s1.top ();} int Getmin () {return s2.top ();}}; int main () {Minstack ms;ms.push (1); Ms.push (2); Ms.push (3); Ms.push (4); Ms.push (5);cout<< "top =" <<ms.top () << "min =" <<ms.getmin () <<endl;ms.pop ();cout<< "top =" <<ms.top () << "min =" < <ms.getmin () <<endl;ms.pop ();cout<< "top =" <<ms.top () << "min =" <<ms.getmin () < <endl;ms.pop ();cout<< "top =" <<ms.top () << "min =" <<ms.getmin () <<endl;ms.pop (); cout<< "top =" <<ms.top () << "min =" <<ms.getmin () <<endl;ms.pop (); System ("pause"); return 0;}
"Leetcode": Min Stack