Algorithm learning-Implementation of the minimum stack O (1) time

Source: Internet
Author: User

Minimum stack

The minimum stack is actually no different from the stack, the only difference is that the minimum stack can be in O (1) time to get the current stack space, the minimum value is how much.

Operation of the minimum stack

The operation of the minimum stack and the operation of the normal stack is not very different, the only way is the Getmin () method, which is used to get the minimum value within the current stack. The other way is push (), Pop (), Top () ... such as

Find a new minimum value in O (n) time

Here is a good, first say the normal O (n) method ~ to get the minimum value in the stack. Is it just to maintain a variable of min? Just! The following examples illustrate.

  • First: We set a stack, and a variable int Min holds the minimum value.
  • Then: Suppose our operation is-push (1), push (2), push (3), push ( -1), push (4)
  • Now: Let's look at the changes in stacks and min.
      stack   1    2    3    -1     4   Min    1    1    1    -1    -1

We find that the Min value is the first time the insertion1The time for1, 4th time Insertion-1The time to become-1, this time we do not feel very simple, only with the maintenance of aMinYou can do it? No! Let's say we do the following:Pop(),Pop()Operation. Let's see what's left in the stack.

      stack   1   2   3

SoMinIt? Still is-1, but in fact-1has been dropped by pop (). If we find that the minimum value is after pop (), how do we updateMinIt? You can only traverse from the beginning, then you need O (n) time.

O (1) approach

Here's how O (1) is found in time, the maintained variables are unchanged, but the elements we hold in the stack need to be associated with the Min value.
Example:
We do the same 5 push operations, the stacking order is 1 2 3-1 4 .

  1. The first stack holds 0, min is 1.
  2. The second stack holds 2-min=1, min<2 so continue for 1.
  3. The third stack holds 3-min=2, min<3 so continue for 1.
  4. The fourth time stack holds -1-min=-2, min>-1 so Min =-1.
  5. The fifth time stack holds 4-min=5, min<5 so continues to be-1.

Do you understand? The number we store is x-min.
This is the push operation, and when we do the pop (), how do we do it, two times pop ()?

First stack top element 5, 5>0, popup, return 5+min=4.
The second stack top element-2, -2<0, pops up, returns min. and update min=min-(-2).

What about the top?

If the top element of the stack is 5, 5>0 returns 5+min.
If the top element of the stack is-2, -2<0 returns min.

Did you find out? In fact, when we press the stack, the element that is pressed into is x-min, then as long as the element pressed into is greater than min, then the deposit is positive, and when X is less than min, the pressed element (x-min) is negative.

So when the stack is played:
When a positive number is encountered, the top element of the stack (x-min) and Min's and (x-min+min) are directly ejected.
A negative number is encountered, indicating that the Min value is updated when the element is pressed, and the Min value at that time is updated to the newly inserted x. For example Min=1, when inserting-1, the stack holds the -1-min=-2, while Min is updated to the new X-Value (-1). Then the moment you pop it, it just pops up. Then we also put the minimum value popped, to update min, updated to the current min-(x next min) Here to compare around, more examples to understand.

Code implementation

I implemented 4 versions, of which the first two versions were O (1) levels, and the latter two were O (n) levels. The 2nd version may have some flaws, if you see the code where the error please comment, thank you.

Container number 1th Implementation

The structure of their own writing.

main.cpp//minstack2////Created by Alps on 14/12/3.//Copyright (c) 2014 Chen. All rights reserved.//#include <iostream> #include <vector>using namespace Std;class minstack {public:vecto    R<int> Stack;    int min;            void push (int x) {if (Stack.empty ()) {stack.push_back (0);        min = x;            }else{Stack.push_back (x-min);            if (x < min) {min = x;        }}} void Pop () {if (Stack.empty ()) {return;            }else{if (stack.back () < 0) {min = Min-stack.back ();        } stack.pop_back ();        }} int Top () {if (Stack.empty ()) {return NULL;        } if (Stack.back () > 0) {return stack.back () +min;        }else{return min;        }} int Getmin () {if (Stack.empty ()) {return NULL; } return min;    }};int Main (int argc, const char * argv[]) {//Insert code here ... std::cout << "Hello, world!\n"; return 0;}


The stack implementation of STL number 2nd

At the edge of the test, my compiler made no mistakes, but OJ reported WA.

main.cpp//minstack4_leetcode////Created by Alps on 14/12/3.//Copyright (c) 2014 Chen. All rights reserved.//#include <iostream> #include <stack>using namespace Std;class minstack{public:stack&    Lt;long> s;    Long min;            void push (int x) {if (S.empty ()) {s.push (0);        min = x;            }else{S.push (x-min);            if (x < min) {min = x;        }}} void Pop () {if (S.empty ()) {return;            }else{if (s.top () < 0) {min = Min-s.top ();        } s.pop ();        }} int Top () {if (S.empty ()) {return NULL;            }else{if (s.top () > 0) {return (int) (Min+s.top ());            }else{return (int) min;        }}} int getmin () {if (S.empty ()) {return NULL;        }else{return (int) min;  }  }};int Main (int argc, const char * argv[]) {int a =-2147483648;    Minstack M;    M.push (2147483646);    M.push (2147483646);    M.push (2147483647);    printf ("%d\n", M.top ());    M.pop ();    printf ("%d\n", M.getmin ());    M.pop ();    printf ("%d\n", M.getmin ());    M.pop ();    M.push (2147483647);    printf ("%d\n", M.top ());    printf ("%d\n", M.getmin ());    M.push (a);    printf ("%d\n", M.top ());    printf ("%d\n", M.getmin ());    M.pop ();    printf ("%d\n", M.getmin ()); return 0;}


3rd Chain List Implementation

Write your own linked list structure.

main.cpp//minstack3_leetcode////Created by Alps on 14/12/3.//Copyright (c) 2014 Chen.        All rights reserved.//#include <iostream>using namespace Std;class minstack {public:struct stacknode{        int num;    Stacknode *next;    };    typedef stacknode* Stack;    Stack s;        Minstack () {s = (stack) malloc (sizeof (struct stacknode));    S->next = NULL;    } int min;            void push (int x) {if (S->next = = NULL) {Stack node = (stack) malloc (sizeof (struct stacknode));            Node->num = x;            Node->next = s->next;            S->next = node;        min = x;            }else{stack node = (stack) malloc (sizeof (struct stacknode));            Node->num = x;            Node->next = s->next;            S->next = node;            if (x < min) {min = x;        }}} void Pop () {if (S->next = = NULL) {return;    }else{        Stack temp = s->next; if (min = = S->next->num && s->next->next! = NULL) {S->next = s->                next->next;                Free (temp);                Min = s->next->num;                        for (Stack loop = s->next; loop! = NULL; loop = Loop->next) {if (min > Loop->num) {                    Min = loop->num;                }}}else{S->next = s->next->next;            Free (temp);        }}} int top () {if (S->next = = null) {return null;    } return s->next->num;        } int Getmin () {if (S->next = = null) {return null;    } return min;    }};int Main (int argc, const char * argv[]) {Minstack MinS;    Mins.push (-1);    Mins.push (0);    Mins.push (2);    Mins.push (-2); printf ("%d\n", MINS.TOP ());    Mins.pop ();    Mins.pop ();    Mins.pop ();    printf ("%d\n", Mins.getmin ()); return 0;}


Container number 4th implementation

The oldest version.

main.cpp//minstack_leetcode////Created by Alps on 14/12/2.//Copyright (c) 2014 Chen. All rights reserved.//#include <iostream> #include "vector" using namespace Std;class minstack {public:struct Stac        knode{int num;    int min;    };    Vector<stacknode> Stack;            void push (int x) {if (Stack.empty ()) {Stacknode S = {x,x};        Stack.push_back (S);                }else{if (x < Stack.back (). min) {Stacknode S = {x,x};            Stack.push_back (S);                }else{Stacknode S = {x,stack.back (). Min};            Stack.push_back (S); }}} void Pop () {if (Stack.empty ()) {}else{Stack.pop_bac        K ();        }} int Top () {if (Stack.empty ()) {return NULL;    } return Stack.back (). Num;        } int Getmin () {if (Stack.empty ()) {return NULL;      }  Return Stack.back (). Min;    }};int Main (int argc, const char * argv[]) {Minstack minstack;    Minstack.push (-1);    Minstack.push (1);    printf ("%d%d\n", Minstack.top (), minstack.getmin ()); return 0;}


Algorithm learning-Implementation of the minimum stack O (1) time

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.