您的位置:首页 > 其它

[LeetCode] Min Stack

2015-06-07 01:40 387 查看
The idea is to use two stacks.

For
push
, the first stack records the pushed elements and the second stack records all the minimum (including duplicates) that have been seen.

For
pop
, we need to compare with the top elements of the two stacks. If they are equal (the top element is also minimum, popping it out will change the minimum), pop both; otherwise, only pop the first stack.

The remaining
top
and
getMin
will be trivial: just return the top element of the first and second stack respectively.

The code is as follows.

class MinStack {
public:
void push(int x) {
if (stk1.empty() || x <= stk2.top())
stk2.push(x);
stk1.push(x);
}

void pop() {
if (stk1.top() == stk2.top())
stk2.pop();
stk1.pop();
}

int top() {
return stk1.top();
}

int getMin() {
return stk2.top();
}
private:
stack<int> stk1;
stack<int> stk2;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: