Title Description:
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 how to save the minimum value, each time when adding data to the stack, always compared with the current minimum value, if it is smaller than the current minimum value, then the current minimum value is pressed into the stack, indicating that the minimum value in the current stack is the current minimum value, and then the new data into the stack. Each time the top element of the stack pops up, the data that pops up is compared to the current minimum value, and if it is equal, indicating that the current minimum value is reached, the number below is the minimum value in the current stack, and it pops up with the new minimum value.
The code is as follows:
Class Minstack { stack<integer> Stack = new stack<integer> (); int min = Integer.max_value; public void push (int x) { if (x <= min) { stack.push (min); min = x; } Stack.push (x); } public void Pop () { int peek = Stack.pop (); if (peek = = min) min = Stack.pop (); } public int Top () { return Stack.peek (); } public int getmin () { return min; }}
Java [Leetcode 155]min Stack