Java [Leetcode 155]min Stack

Source: Internet
Author: User

Title Description:

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.

Problem Solving Ideas:

The main problem is how to save the minimum value, each time when adding data to the stack, always compared with the current minimum value, if it is smaller than the current minimum value, then the current minimum value is pressed into the stack, indicating that the minimum value in the current stack is the current minimum value, and then the new data into the stack. Each time the top element of the stack pops up, the data that pops up is compared to the current minimum value, and if it is equal, indicating that the current minimum value is reached, the number below is the minimum value in the current stack, and it pops up with the new minimum value.

The code is as follows:

Class Minstack {    stack<integer> Stack = new stack<integer> (); int min = Integer.max_value;    public void push (int x) {    if (x <= min) {    stack.push (min);    min = x;    }    Stack.push (x);    }        public void Pop () {    int peek = Stack.pop ();    if (peek = = min)    min = Stack.pop ();    }    public int Top () {        return Stack.peek ();    }    public int getmin () {        return min;    }}

  

Java [Leetcode 155]min Stack

Related Article

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.