To implement a stack, the push, pop, and Min operations only require O (1) time.

Source: Internet
Author: User

Ideas:

The push and pop operations are completed within the constant time complexity. However, the min operation must be completed within the constant time complexity. At first, it is easy to think of saving a variable min in the stack, to save the minimum value, you only need to check the value of the min variable if you need the min () operation. this idea looks good, but there is a fatal defect, that is, if only one min variable is saved, then when min also needs to play the stack, the min in the stack also needs to be updated with the second smallest value. However, we cannot know which second smallest value is. We can also try to save the second smallest variable secmin, when the minimum value is on the stack, we use secmin to update the min variable. However, if secmin is on the stack, thirdmin must be updated, if thirdmin also goes out of the stack ....... in this case, we need to save Min, secmin, thirdmin ...... and so on. therefore, the O (1) variables cannot be satisfied.

Now the problem becomes. We need an extra space to save the current minimum value. Even if the current minimum value is out of the stack, we can still get the latest minimum value (regardless of the stack, how does the stack pressure process change ),

We can try to solve the problem by using the auxiliary Stack:

Store a data stack and a secondary stack in the newly defined stack. The secondary stack top stores the current minimum Min.

Min () operation: you only need to check the top elements of the secondary stack.

Push (_ Val): First press _ Val into the data stack, then compare _ Val with the top element of the secondary stack. If _ Val <= top, press _ Val into the auxiliary stack to make _ Val the current minimum value. Note that _ Val = Top also needs to be written into the stack.

Pop () operation: First play the top element of the data stack to the stack. If the top element of the stack is the minimum value, play the top element of the auxiliary stack (the minimum value is min)

The Code is as follows:

#include<iostream>#include<stack>using namespace std;struct MinStack{private:stack<int> Data;stack<int> Min;public:void push(int val){Data.push(val);if(Min.empty() || val <= Min.top())Min.push(val);}int pop(){if(Data.empty()){cout<<"pop error"<<endl;throw "Error";}int Temp=Data.top();Data.pop();if(Temp == Min.top())Min.pop();return Temp;}int min(){if(Min.empty()){cout<<"No min"<<endl;throw "error!";}return Min.top();}};void main(){MinStack ms;ms.push(2);ms.push(2);ms.push(3);ms.pop();ms.pop();ms.pop();cout<<ms.min();}

The above method is a typical application of time for space. we can have another method without extra space. the original stack structure enables push and pop operations to be completed in O (1) time. now, we focus on the min operation. the min operation can also be completed in O (1) Time. Due to the limitation of the stack structure, we can only save Min on the top of the stack. however, the element at the top of the stack should be the current element, so that our pop operation can be completed within O (1) time. however, it is obviously impossible to simply use the stack top. we can try to use two positions: the top position of the stack and the next position on the top of the stack. The top of the stack stores the current min value, and the next position on the top of the stack stores the current _ Val
-Min value. When pop is required, only two elements need to be popped up or added or subtracted.

Specific Operation: Push (_ Val): If the stack is empty, it is directly pushed into one element twice. If the stack is not empty, replace the top element of the stack with (_ Val-min) and the latest minimum value.

Pop (): two elements are displayed. Based on the positive and negative values of (_ Val-min), add or subtract the top element of the stack.

Min (), obtained directly from the top element of the stack.

Code:

# Include <iostream> # include <stack> using namespace STD; struct minstack {PRIVATE: Stack <int> data; public: void push (INT Val) {If (data. empty () {data. push (VAL); data. push (VAL);} else {int min = data. top (); data. pop (); data. push (Val-min); data. push (Val <min? VAL: min) ;}} int POP () {If (data. Empty () {cout <"Pop error! "<Endl; exit (1);} int min = data. top (); data. pop (); int secmin = data. top (); data. pop (); // two if (secmin <0) when the stack is up and down, // secmin <0 indicates that the pop-up value is the minimum value. You need to use the second smallest value to update the top of the stack {data. push (min-secmin); Return min;} else {// If the pop-up value is not the minimum value, the stack pops up directly without updating the minimum value if (! Data. empty () {data. push (min); Return secmin + min;} return min ;}} int min () {If (data. empty () {cout <"Search min error! "<Endl; exit (1);} int min = data. top (); Return min ;}}; void main () {minstack MS; Ms. pop (); Ms. pop (); Ms. pop (); cout <Ms. min ();}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.