标签:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
class MinStack {
LinkedList<Integer> stack = new LinkedList<>();
Integer min = Integer.MAX_VALUE;
public void push(int x) {
stack.push(x);
if (x < min) {
min = x;
}
}
public void pop() {
stack.pop();
min = Integer.MAX_VALUE;
for (Integer index : stack) {
if (index < min) {
min = index;
}
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}LinkedList<Integer> stack = new LinkedList<Integer>();
LinkedList<Integer> minStack = new LinkedList<Integer>();
int min = Integer.MAX_VALUE;
public void push(int x) {
stack.push(x);
minStack.push(min);
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}class MinStack {
LinkedList<Integer> stack = new LinkedList<Integer>();
LinkedList<Integer> minStack = new LinkedList<Integer>();
int min = Integer.MAX_VALUE;
public void push(int x) {
stack.push(x);
if (min >= x) {
min = x;
minStack.push(min);
}
}
public void pop() {
if (min == stack.peek()) {
minStack.pop();
if (minStack.isEmpty()) {
min = Integer.MAX_VALUE;
} else {
min = minStack.peek();
}
}
stack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
}
LinkedList<Long> stack = new LinkedList<>();
long min = Integer.MAX_VALUE;
public void push(int x) {
if (stack.isEmpty()) {
stack.push(0L);
min = x;
} else {
stack.push(x-min);
if (x < min) {
min = x;
}
}
}
public void pop() {
long pop = stack.pop();
if (pop < 0) {
min -= pop;
}
}
public int top() {
long top = stack.peek();
if (top > 0) {
return (int) (top+min);
} else {
return (int) min;
}
}
public int getMin() {
return (int) min;
}运行效率最好的方法!!!标签:
原文地址:http://blog.csdn.net/my_jobs/article/details/43525599