Version #2 One Stack[TODO]
Version #1 Two Stacks
二刷
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
stack.push(x);
if (minStack.isEmpty() || x < minStack.peek()) {
minStack.push(x);
} else {
minStack.push(minStack.peek());
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
一刷
public class MinStack {
Version #1 Two Stacks
二刷
class MinStack {
private Stack<Integer> stack;
private Stack<Integer> minStack;
/** initialize your data structure here. */
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int x) {
stack.push(x);
if (minStack.isEmpty() || x < minStack.peek()) {
minStack.push(x);
} else {
minStack.push(minStack.peek());
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
一刷
public class MinStack {
private Stack<Integer> minStack;
private Stack<Integer> numStack;
/** initialize your data structure here. */
public MinStack() {
minStack = new Stack<Integer>();
numStack = new Stack<Integer>();
}
public void push(int x) {
numStack.push(x);
if (minStack.isEmpty() || x <= minStack.peek()) minStack.push(x);
}
public void pop() {
if (numStack.isEmpty()) return;
int num = numStack.pop();
if (minStack.peek() == num) minStack.pop();
}
public int top() {
if (numStack.isEmpty()) return Integer.MIN_VALUE;
return numStack.peek();
}
public int getMin() {
return minStack.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();
*/
No comments:
Post a Comment