根据您的实际需求,您可以进行另一种折衷。
在1个Integer对象的存储成本,你可以用复杂性让您的最大值O(1)不排序,用O(1)成本PUSH与为O(n)成本时从堆栈中弹出元素。
public class IntStackWithMax {
private Integer maxVal = Integer.MIN_VALUE;
private Vector<Integer> values = new Vector<Integer>();
// cost O(1)
public Integer getMaxVal() {
return maxVal;
}
//cost O(1)
public boolean push(Integer item) {
maxVal = Math.max(maxVal, item);
return values.add(item);
}
//cost O(n) (!!!)
public Integer pop() {
Integer result = values.remove(values.size() - 1);
maxVal = Collections.max(values);
return result;
}
//cost O(1)
public Integer peek() {
return values.lastElement();
}
}
也请注意,这是不线程安全的。
为什么'Stack'?或者任何“收藏”?它不可能。 – Andremoniy
它是不可能的。您访问的最后一个值始终可以具有最大值。 – vish4071
如果你不能用'O(log(n))'(比如Binary Search Tree)或'O(1)'(比如Hash Table)实现搜索的数据结构来更改'Stack',那么我认为你不可能获得比线性更好的性能。 –