Leetcode[stack]: 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.

This solution on the discuss: Https://oj.leetcode.com/discuss/15679/share-my-java-solution-with-only-one-stack is very ingenious, The key to the algorithm is to save the difference between the current element and the smallest element with a stack. To avoid integer.maxvalue-integer.minvalue this exception, use a long type to save. The Java code is as follows:

 Public classMinstack {LongMin Stack<long> Stack; Public Minstack() {stack=NewStack<> (); } Public void Push(intx) {if(Stack.isempty ()) {Stack.push (0L);        Min=x; }Else{Stack.push (x-min);//could is negative if min value needs to change            if(x<min) min=x; }    } Public void Pop() {if(Stack.isempty ())return;LongPop=stack.pop ();if(pop<0) Min=min-pop;//if negative, increase the Min value} Public int Top() {LongTop=stack.peek ();if(top>0){return(int) (top+min); }Else{return(int) (min); }    } Public int Getmin() {return(int) min; }}

The time performance of this algorithm is as follows:

But I get "Memory Limit exceeded" when I implement the same algorithm in C + +, because when I use a long type, it's actually two stacks. Still, the idea of this algorithm is worth learning.

Leetcode[stack]: 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.