问题:
解题:
分析:需要一个链表实现先进先出,用一个树来实现计数桶,这样时间复杂度都是O(1),不过这个执行时间和空间优化没想好
class MaxQueue {
/**
* 链表
*/
private LinkedList<Integer> list = new LinkedList<>();
/**
* 计数桶
*/
private TreeMap<Integer, Integer> tree = new TreeMap<>();
public MaxQueue() {
}
public int max_value() {
if (tree.isEmpty()) {
return -1;
}
return tree.lastKey();
}
public void push_back(int value) {
list.addLast(value);
Integer treeInt = tree.get(value);
if (null == treeInt) {
tree.put(value, 1);
} else {
tree.put(value, ++treeInt);
}
}
public int pop_front() {
Integer value = list.pollFirst();
if (null == value) {
return -1;
}
Integer treeInt = tree.get(value);
if (treeInt != null) {
if (treeInt > 1) {
tree.put(value, --treeInt);
} else {
tree.remove(value);
}
}
return value;
}
}
/**
* 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();
*/
性能:
目前优化空间比较大