IT company 100-design stack with min function

Source: Internet
Author: User

Problem Description:

Defines the data structure of the stack, requiring the addition of a min function to get the smallest element of the stack.

The time complexity required for the function min, push, and Pop is O (1).

Double Space Implementation:

Save 2 stacks, each of which is the element and the current minimum value.

Compact Space Implementation:

Code implementation:

package oschina.mianshi;/** *  @project: oschina *  @filename: it2.java  *  @version: 0.10 *  @author: jm han *  @date:  17:08 2015/10/20  *  @comment: test purpose *  @result:  */import java.util.stack;import  static tool.util.*;class MinStack{   Stack<Integer> stacks,  Mins;   minstack () {      stacks = new stack< Integer> ();      mins   = new stack<integer> () ;    }   void push (integer x) {       Stacks.push (x);       //<=  instead of < is for repeating elements        if (Mins.isempty ()  | |  x <= mins.peek ())          mins.push (x);   }   void pop () {      integer x =  stacks.pop ();       if (X == mins.peek ())           mins.pop ();    }   integer peek () {       return stacks.peek ();    }   integer getmin () {       return mins.peek ();    }}public class it2  {   public static void main (String[] args)  {       minstack minstack = new minstack ();       Minstack.push (6);       minstack.push (2);       Minstack.push (3);       minstack.push (1);       Minstack.push (1);  &nbsP;    minstack.push (5);       minstack.push (8);       system.out.println ("min value: "  + minstack.getmin ());       minstack.pop ();       minstack.pop ();       minstack.pop ();       minstack.pop ();       system.out.println ("min value: "  + minstack.getmin ());    }}

Output:

Min Value:1min value:2


IT company 100-design stack with min function

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.