Question: Queue with two stacks. Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.
问题描述: 这里的问题是想要使用两个堆栈来实现的队列。
解决方案: 这里主要的算法就是现将元素压入栈1,再从栈1弹出去这个元素并将其压到栈2。具体实现的伪代码如下:
- Enqueue: 将所有元素压入到栈1里面去
- Dequeue Operation : 如果栈2是空, 将栈1的所有元素压入到栈2
Question: Stack with max. Create a data structure that efficiently supports the stack operations (push and pop) and also a return-the-maximum operation. Assume the elements are reals numbers so that you can compare them.
问题描述: 这里就是要求含有一个寻找最大元素方法的栈的实现。
解决方案: 使用两个堆栈,一个包含所有元素,另一个包含最大值。 要添加一个元素,压到第一个栈里面去; 如果它大于第二
coursera算法公开课练习题Interview(3)
最新推荐文章于 2019-04-15 11:41:58 发布