Implement the functions for a stack and function getMinimum() all with O(1) complexity.
Utilisateur anonyme
We need two stacks to solve this problem. For stack 1, it is used to implement the normal push(), pop() and top() functions. And for stack 2, we maintain the minimum element in stack 1 as its top. We maintain stack 2 in the following way: 1) While pushing an element into stack 1, we compare this element with the top element in stack 2. If it is smaller, we push this element into stack 2 at the same time. Otherwise, we do nothing. 2) When pop an element out from stack 1, we compare this element with the top element in stack 2. If they are equal, we pop out the top element from stack 2 at the same time. Otherwise, we do nothing.