做面试题59 - II. 队列的最大值时遇见个bug
public int pop_front() {
if(q.isEmpty()) return -1;
//int val = q.poll();
if(q.peek() == d.peekFirst()){
d.poll();
}
return q.poll();
}
不能通过
public int pop_front() {
if(q.isEmpty()) return -1;
int val = q.poll();
if(val == d.peekFirst()){
d.poll();
}
return val;
}
能通过
总代码
class MaxQueue {
private Queue<Integer> q;
private Deque<Integer> d;
//int length;
public MaxQueue() {
q = new LinkedList<>();
d = new ArrayDeque<>();
}
public int max_value() {
return q.isEmpty() ? -1 : d.peekFirst();
}
public void push_back(int value) {
q.add(value);
while(!d.isEmpty() && value > d.peekLast()){
d.pollLast();
}
d.addLast(value);
}
public int pop_front() {
if(q.isEmpty()) return -1;
int val = q.poll();
if(val == d.peekFirst()){
d.poll();
}
return val;
}
}
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue obj = new MaxQueue();
* int param_1 = obj.max_value();
* obj.push_back(value);
* int param_3 = obj.pop_front();
*/
.peek()方法返回的是Integer类型,没有及时转成int,可以用(int)强转