题目:
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.min(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.min(); --> 返回 -2.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
我的思路:
关键就在于都需要o(1)时间内完成,所以感觉需要有个东西来记录最小值,设置一个cutmin来记录当前最小值,这样每次min的时候,输出栈顶元素的cutmin就可以在o(1)时间内完成了。这个栈感觉用链表或者是数组都可以。当然有用STL的,我还是先自己写了。
struct node
{
long data;
long cutmin;
node* link;
node* left;
};
class MinStack {
public:
/** initialize your data structure here. */
node*head;
MinStack()
{
head=new node;
head->data=-9999;
head->left=NULL;
}
void push(int x) {
if(head->data==-9999)
{
head->data=x;
head->cutmin=x;
}
else
{
node* p=new node;
p->data=x;
if(head->cutmin<x) p->cutmin=head->cutmin;
else p->cutmin=x;
head->link=p;
p->left=head;
head=head->link;
}
}
void pop() {
if (head->left == NULL)
{
head->data = -9999;
head->link = NULL;
}
else
{
head = head->left;
head->link = NULL;
}
}
int top() {
return head->data;
}
int min() {
return head->cutmin;
}
};
dalao的思路:
他构建了一个数据栈用来完成pop,push,top这样的常规操作。又弄了一个辅助栈,专门用它记录当前的最小值。原理很简单。这个我也想到基本就是一个制表的感觉,但是我总觉得辅助栈会空?还是自己水。
每次要push (好比是3) 的时候,如果要push进去的东西(3),比辅助栈栈顶元素(好比是4)小,就往辅助栈push(3)这样辅助栈栈顶永远是最小的元素。
每次pop的时候,只有数据栈顶和辅助栈顶相等才让辅助栈顶pop出来。
class MinStack {
public:
/** initialize your data structure here. */
stack<int> data, help;
MinStack() {
}
void push(int x) {
data.push(x);
// 如果x是data和help的第一个元素,或者x小于等于help的最小元素,入栈
if(help.empty() || x <= help.top()) help.push(x);
if(x > help.top())
{
// 如果x大于help的最小元素,向help中再压入一遍该最小元素,保持两个栈元素个数相等
// 比如data里现在有3,help里现在也有3,data里压入一个4,那么help里压入一个3
// 这样如果把data的4弹出,我们同步把help的3也弹出
int temp = help.top();
help.push(temp);
}
}
void pop() {
if(!data.empty() && !help.empty())
{
data.pop();
help.pop();
}
}
int top() {
return data.top();
}
int min() {
return help.top();
}
};
作者:superkakayong
链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof/solution/zi-jie-ti-ku-jian-30-jian-dan-bao-han-minhan-shu-d/