LintCode-Min Stack

本文介绍了一种使用双栈实现带有min()功能的栈,可在O(1)时间内完成push、pop和min操作,详细解释了算法原理及其实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Implement a stack with min() function, which will return the smallest number in the stack.

It should support push, pop and min operation all in O(1) cost.

  • 题目模板

    class MinStack {
    public:
      MinStack(){}
      /*
       * @param number: An integer
       * @return: nothing
       */
      void push(int number) {
          // write your code here
      }
    
      /*
       * @return: An integer
       */
      int pop() {
          // write your code here
      }
    
      /*
       * @return: An integer
       */
      int min() {
          // write your code here
      }
    };
    
  • 题目大意

    让你维护一个最小值栈,每次可以获得这个栈中的最小值。

  • 大概思路

    这道题好像以前做过,所以还是比较简单的。双栈来实现,一个栈是正常的,另一个栈负责维护第一个栈中的最小值。两个栈可以不是同步升降的,只有当第一个栈新加的数据小于等于第二个栈栈顶的数据时,才把这个数加到第二个栈里面。这里写小于等于是考虑到同时加两个最小值进来的情况。

    class MinStack {
    private:
    stack<int> s, smin;
    public:
      MinStack(){}
    
      /*
       * @param number: An integer
       * @return: nothing
       */
      void push(int number) {
          // write your code here
          s.push(number);
          if(smin.empty())
            smin.push(number);
          else if(number <= smin.top())
              smin.push(number);
      }
    
      /*
       * @return: An integer
       */
      int pop() {
          // write your code here
          if(s.top() == smin.top())
            smin.pop();
          int t = s.top();
          s.pop();
          return t;
      }
    
      /*
       * @return: An integer
       */
      int min() {
          // write your code here
          return smin.top();
      }
    };
    
  • 细节方面

    注意在pop()的时候要把栈里的值弹出来一个。

  • 题目链接:https://www.lintcode.com/problem/min-stack/description

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值