# Min Stack Solution

Source: Internet
Author: User

Question

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.
Solution

Original thinking is-to-use-stacks, one-to-store input elements, and the other are to store current min value.

However, there is an improvement.

This stack was to store diff between input value and the current min value.

If current value < min value, we set min as current imput value.

Therefore, when we pop or peek each element in stack, we know:

If it's greater than 0, then it must is greater than current min value.

If It's smaller than 0, then it must equal to current min value.

`1 classMinstack {2Stack<long>diff;3     Private Longmin;4     5      PublicMinstack () {6Min =Integer.max_value;7diff =NewStack<long>();8     }9      Public voidPushintx) {TenDiff.push ((Long) x-min); Onemin = x < min?x:min; A     } -      Public voidpop () { -         if(Diff.size () < 1) the             return; -         LongTMP =Diff.pop (); -         if(TMP < 0) -Min-=tmp; +     } -      Public intTop () { +         LongTMP =Diff.peek (); A         if(TMP < 0) atTMP =min; -         Else -TMP + =min; -         return(int) tmp; -     } -      Public intgetmin () { in         return(int) min; -     } to}`

Min Stack Solution

Related Keywords:

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.