编程之美上的一个题目。
感觉上面用数组的方法不是很好理解。于是自己写了一下。也是用了两个栈来维护一个队列。同时又多出两个栈,分别维护之前两个栈里面的最大值。然后求Max函数的时候,值需要返回后两个栈的的最大值即可。
看代码:
package a;
import java.util.Stack;
public class Test1 {
public static void main(String s[]) {
//5 6 3 7 2 1
QueueM q = new QueueM();
q.enqueue(5);
int m = q.max();
q.enqueue(6);
m = q.max();
q.enqueue(3);
int d = q.dequeue();
q.enqueue(7);
m = q.max();
q.enqueue(2);
m = q.max();
q.enqueue(1);
d = q.dequeue();
m = q.max();
d = q.dequeue();
m = q.max();
d = q.dequeue();
m = q.max();
}
}
class QueueM {
static final int INF = 111111111;
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack1_m = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
Stack<Integer> stack2_m = new Stack<Integer>();
public void enqueue(int obj) {
stack1.push(obj);
if (stack1_m.size() == 0) {
stack1_m.push(obj);
} else {
int d = stack1_m.peek();
if (d < obj) {
stack1_m.push(obj);
} else {
stack1_m.push(d);
}
}
}
public int dequeue() {
if (stack2.isEmpty()) {
int n = stack1.size();
for (int i = 0; i < n; i++) {
int d = stack1.pop();
stack1_m.pop();
stack2.push(d);
if (stack2_m.size() == 0) {
stack2_m.push(d);
} else {
if (d > stack2_m.peek()) {
stack2_m.push(d);
} else {
stack2_m.push(stack2_m.peek());
}
}
}
}
if (stack2.isEmpty()) {
return INF * -1;
} else {
int d = stack2.pop();
stack2_m.pop();// 相应位置的最大值也出栈
return d;
}
}
public int max() {
if (stack1_m.size() == 0 && stack2_m.size() == 0) {
return -1 * INF;
}
if (stack1_m.size() == 0 && stack2_m.size() != 0) {
return stack2_m.peek();
}
if (stack1_m.size() != 0 && stack2_m.size() == 0) {
return stack1_m.peek();
}
return stack1_m.peek() > stack2_m.peek() ? stack1_m.peek() : stack2_m
.peek();
}
}
代码中的max()函数就是返回了两个栈里的 最大值。这样,就很好理解了。比直接用数组好理解的多。
题目中我用563721这几个数字来模拟操作。思路与何海涛的书中求栈的最大值的思路类似。