Sword offer--contains the stack of min function

Source: Internet
Author: User
Tags min
Title Description:

Define the data structure of the stack, implement a min function that can get the smallest element of the stack in the type. Ideas:

Because each time the element into the stack can not guarantee that the top element is the smallest, so need to find a way to make the top element of the stack is always the smallest element, sorting is a kind of thinking, but each sort also designed to re-stack and into the stack, think it should not be so.
One idea is that you can use a secondary stack , which is equivalent to a space-time change. The specific idea is: when the new element into the stack of the original stack top element is small, the element is placed in a secondary stack, if the new stack of elements than the original stack top element, then in the secondary stack to continue to put the smallest element. This goes on and on, when the smallest element needs to be taken, the top element of the stack is taken from the auxiliary stack, so the complexity of the time is O (1). And one of the benefits of doing this is that after the smallest element, the next small element (still the smallest) is taken. Code implementation:

import java.util.Stack;
    public class Solution {stack<integer> data = new stack<integer> ();
    stack<integer> assist = new stack<integer> ();
        public void push (int node) {Data.push (node);
        if (assist.size () = = 0 | | Node < Assist.peek ()) {Assist.push (node);
        }else{Assist.push (Assist.peek ());
            }} public void Pop () {if (data.size () > 0 && assist.size () >0) {Data.pop ();
        Assist.pop ();
        }} public int top () {if (data.size () > 0) {return data.peek ();
    } return-1; 
        } public int min () {if (Data.size () >0 && assist.size () > 0) {return assist.peek ();
    } return-1; }

}

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.