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.
- 首次解题思路
对每个结点增加一个最小值成员,该成员表示当该结点是栈顶元素时最小值的大小。结果提交之后LeetCode
返回了Memory limited Error
错误。 - 首次尝试的代码
struct LinkNode
{
int data;
int min;
LinkNode* next;
};
class MinStack {
public:
MinStack():high(NULL){
}
void push(int x) {
LinkNode* node = new LinkNode;
node->data = x;
if (high == NULL)
{
node->min = x;
}
else
{
int temp = x < high->min ? x : high->min;
node->min = temp;
}
node->next = high;
high = node;
}
void pop() {
if (high)
{
LinkNode* temp = high;
high = high->next;
delete temp;
}
}
int top() {
if (high)
{
return high->data;
}
}
int getMin() {
return high->min;
}
private:
LinkNode* high;
};
- 第二次解题思路
用两个标准库的栈来维护这个MinStack
,一个栈保存元素,另一个栈保存最小值。此时,可以对第二个栈的大小进行压缩。 - 实现代码
/*************************************************************
* @Author : 楚兴
* @Date : 2015/2/8 16:17
* @Status : Accepted
* @Runtime : 71 ms
*************************************************************/
#include <iostream>
#include <stack>
using namespace std;
class MinStack {
public:
stack<int> num;
stack<int> min;
void push(int x) {
if (min.size() == 0)
{
min.push(x);
}
else
{
if (x <= min.top())
{
min.push(x);
}
}
num.push(x);
}
void pop() {
if (!num.empty())
{
if (num.top() == min.top())
{
min.pop();
}
num.pop();
}
}
int top() {
if (!num.empty())
{
return num.top();
}
}
int getMin() {
if (!num.empty())
{
return min.top();
}
}
};
时间: 2024-10-12 05:46:07