Statistics O(1)模式下的堆栈
有什么方法可以跟踪堆栈并在O1时间内获取Is模式Statistics O(1)模式下的堆栈,statistics,stack,Statistics,Stack,有什么方法可以跟踪堆栈并在O1时间内获取Is模式 我知道我已尝试实现最小或最大堆栈。但是这个对我来说是新的。有什么想法吗?这个想法与最小堆栈或最大堆栈是一样的,只是现在我们必须跟踪堆栈中元素的计数,这样我们就可以确定新推的元素是否改变了模式。您可以将其推广到任何操作,在这些操作中,您可以提供一个可能有状态的函数currentValue,beingpush->nextValue,并保证弹出返回到上一个值 public class ModeStack<T> { private f
我知道我已尝试实现最小或最大堆栈。但是这个对我来说是新的。有什么想法吗?这个想法与最小堆栈或最大堆栈是一样的,只是现在我们必须跟踪堆栈中元素的计数,这样我们就可以确定新推的元素是否改变了模式。您可以将其推广到任何操作,在这些操作中,您可以提供一个可能有状态的函数currentValue,beingpush->nextValue,并保证弹出返回到上一个值
public class ModeStack<T> {
private final Deque<T> stack = new ArrayDeque<>(), modeStack = new ArrayDeque<>();
private final Map<T, Integer> count = new HashMap<>();
public ModeStack() {}
public void push(T t) {
stack.push(t);
int tCount = count.getOrDefault(t, 0)+1;
count.put(t, tCount);
if (modeStack.isEmpty())
modeStack.push(t);
else
modeStack.push(tCount > count.get(modeStack.peek())
? t : modeStack.peek());
}
//throws NoSuchElementException if stack is empty
public T pop() {
int newCount = count.get(stack.peek())-1;
//remove unneeded map entries to prevent memory retention
if (newCount == 0)
count.remove(stack.peek());
else
count.put(stack.peek(), newCount);
modeStack.pop();
return stack.pop();
}
//returns null if stack is empty; ties broken by earliest-value-first
public T mode() {
return modeStack.peek();
}
public static void main(String[] args) {
ModeStack<Integer> s = new ModeStack<>();
s.push(1);
System.out.println(s.mode());
s.push(2);
s.push(2);
System.out.println(s.mode());
s.pop();
System.out.println(s.mode());
}
}
维护贴图不会改变渐进空间复杂度,因为在最坏的情况下,所有关键点都映射为1,贴图的大小为n-但元素堆栈和模式堆栈的大小也为n,因此,总空间使用率已启用。听起来您还需要一个哈希表来将值映射到计数。是的,我可以这样做,但这会增加空间复杂性吗?此外,如何获取O1中最大值的密钥?我必须扫描地图的整个入口集?您需要将其与用于最小/最大堆栈的相同技巧结合起来。