读书人

Chapter 三 Stacks and Queues - 3.2

发布时间: 2012-07-18 12:05:38 作者: rapoo

Chapter 3 Stacks and Queues - 3.2
problem 3.2: How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.

At first, I thought it was impossible to impement such a stack. However, when I turned to the answer page, I found that I ignored the most important property of stacks, FILO (First In Last Out). Each element in a stack can keep properties of all elements beneath it, for all elements below won't be changed before the element is removed. It means that we can record the minimum value of all elements in the element above them. When an element is at the top of the stack, the minimum value it keeps is the minimum value of all elements in the stack.

The lesson is: you can achieve quite high performance if you sacrifice space. If you cannot achieve performance that is high enougth, you didn't sacrifice enough space.

读书人网 >编程

热点推荐