categories: leetcode
题目描述
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.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); —> Returns -3.
minStack.pop();
minStack.top(); —> Returns 0.
minStack.getMin(); —> Returns -2.
参考代码
class MinStack {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
/** initialize your data structure here. */
public MinStack() {
stackData = new Stack<Integer>();
stackMin = new Stack<Integer>();
}
public void push(int x) {
stackData.push(x);
if(stackMin.isEmpty() || x <= stackMin.peek()) {//最小值栈的为空或这最小值小于等于
stackMin.push(x);
}
}
public void pop() {
Integer num = stackData.pop();
if(num.equals(stackMin.peek())) {//要用equals函数
stackMin.pop();
}
}
public int top() {
return stackData.peek();
}
public int getMin() {
return stackMin.peek();
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
思路及总结
利用两个栈,一个代表最小值,一个代表普通情况。注意最小值栈要依靠普通栈,普通栈中最小值出栈,最小值栈的最小值也要出栈。另外自己基础太差,wrong answer的时候一直没发现要用equals才能进行更合理的比较。希望自己以后更深入的时候能有更好的理解。
参考
https://blog.csdn.net/loophome/article/details/83749444
https://blog.csdn.net/returnzhang/article/details/78608898