Leetcode Min Stack

Source: Internet
Author: User

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.
Thinking Analysis: The main study of the use of the stack, the only tricky is how to get the minimum value in constant time, we can consider using two stacks, a stack seqstack to maintain the order of the stack, operations with the normal stack, the other minstack stack for maintaining the minimum value, When there is a smaller or equal number than the top element of the stack, the stack is placed so that the top element is always the minimum value. This way the Getmin function simply takes the top element of the stack that maintains the minimum value. An error-prone place is to delete elements in addition to removing the top element from the Seqstack, but also need to check from the top of the Minstack stack, if the deletion is just the smallest element, should be the top of the Minstack stack is also deleted. AC Code
Class Minstack {    stack<integer> seqstack = new stack<integer> ();    stack<integer> minstack = new stack<integer> ();    public void push (int x) {        int curmin;        if (Minstack.isempty ()) {            curmin = integer.max_value;        } else{            curmin = Minstack.peek ();        }        if (x <= curmin) Minstack.push (x);        Seqstack.push (x);    }    public void Pop () {        if (Seqstack.isempty ()) return;        else {            int removedvalue = Seqstack.pop ();            if (Removedvalue = = Minstack.peek ()) {                minstack.pop ();}}    }    public int Top () {        return Seqstack.peek ();    }    public int getmin () {        return Minstack.peek ();    }}


Leetcode Min Stack

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.