[LeetCode] Min Stack

本文介绍了一种能在常数时间内完成压栈、弹栈、获取栈顶元素及最小元素的MinStack设计方法。通过使用两个标准库栈分别保存元素及其对应最小值,确保了操作效率。

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();
        }       
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值