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