设计一个栈,出栈时弹出栈中最小的元素,时间复杂度为1

本文介绍了一种特殊的数据结构——最小值栈的实现方法。该栈能够在常数时间内完成元素的压入与弹出操作,并确保每次弹出的都是当前栈内的最小值。通过维护两个栈,一个用于存储数据,另一个用于跟踪最小值,从而实现了高效的插入和删除操作。

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

Given a few numbers, how will you push them into a stack such that whenever I pop the top most element from that stack, I get the minimum number from the bunch. Also he wanted me to tell the pop push algorithm such that the order of insertion and popping should be O(1).


template <typename T>
class MinStack {
private:
  std::stack<T> stack;
  std::stack<T> min;
public:
  MinStack() {}
  void push(T elem) {
    stack.push(elem);
    min.push(std::min(elem, min.top());
  }
  std::pair<T, T> popValAndMin() {
    T val = stack.top();
    T minVal = min.top();
    stack.pop();
    min.pop();
    return minVal;
  }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值