[剑指Offer] 20.包含min函数的栈

时间:2023-03-10 00:07:32
[剑指Offer] 20.包含min函数的栈

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

【思路1】两个栈Stack和Min,Stack为当前栈中元素,Min为与Stack中元素一一对应的当前栈最小值。

 class Solution
{
public:
stack<int> Stack;
stack<int> Min;
void push(int value)
{
Stack.push(value);
if(!Min.empty() && Min.top() < value) 
value = Min.top();
Min.push(value);
}    
void pop()
{
Stack.pop();
Min.pop();
}    
int top()
{
return Stack.top();
}    
int min()
{
return Min.top();
}
};

【思路2】使用pair<int,int>从而实现只用一个栈来操作

 class Solution
{
public:
stack< pair<int,int> > Stack;
int Min(int a,int b)
{
return (a < b)?a:b;
}
void push(int value)
{
Stack.push(pair<int,int>(value, Stack.empty()?value:Min(value,min())));
}    
void pop()
{
Stack.pop();
}    
int top()
{
return Stack.top().first;
}    
int min()
{
return Stack.top().second;
}
};