topic
To define the data structure of the stack, please implement a min function that can get the smallest element of the stack in this type. In this stack, the time complexity of calling min, push and pop is O(1).
MinStack minStack = new MinStack();
myStack.push(-2);
myStack.push(0);
myStack.push(-3);
myStack.min(); --> returns -3.
myStack.pop();
myStack.top(); --> 内容 0.
minStack.min(); --> returns -2.
Tip:
The total number of calls to each function does not exceed 20,000 times
accomplish
- The number of function calls is limited, so min cannot directly traverse the size, choose to use two stacks, stack B is used to store smaller numbers, and is arranged in strict descending order.
- B is not empty until A is empty!
class MinStack {
Stack<Integer> A, B;
public MinStack() {
A = new Stack<>();#栈
B = new Stack<>();
}
public void push(int x) {
A.add(x);
if(B.empty() || B.peek() >= x)
B.add(x);
}
public void pop() {
if(A.pop().equals(B.peek()))
B.pop();
}
public int top() {
return A.peek();
}
public int min() {
return B.peek();
}
}
class MinStack:
def __init__(self):
self.A, self.B = [], []
def push(self, x: int) -> None:
self.A.append(x)
if not self.B or self.B[-1] >= x:
self.B.append(x)
def pop(self) -> None:
if self.A.pop() == self.B[-1]:
self.B.pop()
def top(self) -> int:
return self.A[-1]
def min(self) -> int:
return self.B[-1]
Summarize
- Stack, add(x), peek(), pop() delete the top element of the stack, empty()
- In the Java code, since the Stack stores the int wrapper class Integer, it is necessary to use equals() instead of == to compare whether the values are equal.
- List,append(x),A[-1],pop()