[Leetcode] Min Stack min stacks

Source: Internet
Author: User

Min Stack


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 getting the current minimum value. We can store the current minimum value with a dynamic array min. If the newly pressed element is greater than the last element of the dynamic array min, no action is made. Otherwise (less than or equal to) is pressed into the min. At the time of the stack, if the stack element equals the last element of Min, the min array is stacked. This enables constant time to find the minimum value in the stack. Here's the code:
Class Minstack {Public:minstack () {capcity=2;        data = new Int[capcity];                size=0;        mincapcity=2;        min = new Int[mincapcity];    minSize = 0;        } ~minstack () {delete[] data;    delete[] min;            } void push (int x) {if (size>=capcity) {int* p=data;            capcity = 2*capcity;            Data=new Int[capcity];            std::memcpy (data, p, sizeof (int) *size);        Delete[] p;                } data[size++]=x;        if (minsize==0) {min[minsize++]=x;                }else if (min[minsize-1]>=x) {if (minsize>=mincapcity) {int* p=min;                mincapcity = 2*mincapcity;                min = new Int[mincapcity];                std::memcpy (min, p, sizeof (int) *minsize);            Delete[] p;        } min[minsize++]=x;            }} void Pop () {if (size>0) {size--;         if (Data[size]==min[minsize-1]) {       minsize--;        }}else{throw exception ();        }} int Top () {if (size>0) {return data[size-1];        }else{throw exception ();    }} int Getmin () {return min[minsize-1];    }private:int size;    int capcity;    int* min;    int minSize;    int mincapcity; int* data;};

[Leetcode] Min Stack min stacks

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.