leetcode Min Stack

来源:互联网 发布:淘宝上旗舰店是真的吗 编辑:程序博客网 时间:2024/04/29 14:26

Min Stack

My Submissions
Total Accepted: 44056 Total Submissions: 221468 Difficulty: Easy

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.
网上都是使用两个堆栈,起初不明白为啥可以这样。
建立两个堆栈,data,mindata。一个存放所有数据,一个存放最小的。
入栈:当x小于等于mindata栈顶元素时候,将x压入栈中。
出栈:如果data.top与mindata.top相等时候,mindata要出栈。
栈的特征就是后入先出,所以可以这样。
class MinStack {
public:
void push(int x)
{
data.push(x);
if (mindata.empty() || mindata.top() >= x)
mindata.push(x);
}


void pop()
{
if (mindata.top() == data.top())
mindata.pop();
data.pop();


}


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


int getMin()
{
return  mindata.top();
}


private:
stack<int> data;
stack<int> mindata;
};
0 0