题目描述:
Implement a stack with min() function, which will return the smallest number in the stack.
It should support push, pop and min operation all in O(1) cost.
Notice
min operation will never be called if there is no number in the stack.
Example
题目思路:
push(1)
pop() // return 1
push(2)
push(3)
min() // return 2
push(1)
min() // return 1
这题要求O(1)的时间复杂度。如果我们用一个sorted数据结构,比如map或者set去做,那么每次query的时间为O(logn),不满足题意。如果要达到要求,必须在建立stack的时候,就产生一个min的信息。在这里,我用两个stack在class中:一个stack为正常的stack,一个为min stack。也就是说,min stack在push的时候还是push一个number,但是这个number永远比已经在min stack中的数小:如果top number大于要push的number,min stack就push这个number;反之,就把top number再push一遍。这样,就保证了top number永远是整个stack的最小值。
Mycode(AC = 15ms):
class MinStack {
private:
stack<int> s;
stack<int> min_stack;
public:
MinStack() {
// do initialization if necessary
}
void push(int number) {
// write your code here
s.push(number);
if (min_stack.empty() || min_stack.top() >= number) {
min_stack.push(number);
}
else {
min_stack.push(min_stack.top());
}
}
int pop() {
// write your code here
int top = s.top();
s.pop();
min_stack.pop();
return top;
}
int min() {
// write your code here
return min_stack.top();
}
};