[Leetcode] Min Stack

Source: Internet
Author: User

The idea was to use the stacks.

pushfor, the first stack records the pushed elements and the second stacks records all the minimum (including du Plicates) that has been seen.

popfor, we need-compare with the top elements of the stacks. If They is equal (the top element is also minimum, popping it out would change the minimum), pop both; Otherwise, only pops the first stack.

The remaining and would be trivial:just return the top element of the first and top getMin second stack respectively.

The code is as follows.

1 classMinstack {2  Public:3     voidPushintx) {4         if(Stk1.empty () | | | x <=stk2.top ())5 Stk2.push (x);6 Stk1.push (x);7     }8 9     voidpop () {Ten         if(Stk1.top () = =stk2.top ()) One Stk2.pop (); A Stk1.pop (); -     } -  the     intTop () { -         returnstk1.top (); -     } -  +     intgetmin () { -         returnstk2.top (); +     } A Private: atstack<int>Stk1; -stack<int>stk2; -};

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