设计一个栈,出栈时弹出栈中最小的元素,时间复杂度为1
2012-09-02 22:31
253 查看
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).
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; } };
相关文章推荐
- 实现一个栈(元素遵守先入后出顺序),能够通过 min 方法在 O(1)时间内获取栈中的最小元素。同时,栈的基本操作:入栈(Push)、出栈(Pop),也是在O(1)时间内完成的
- 用时间复杂度O(1)的算法求栈中的最小元素
- 设计一个栈,提供一个函数能够找出栈内最大的元素,时间复杂度为O(1)
- O(1)时间复杂度实现入栈、出栈、获得栈中最小元素、获得栈中最大元素
- Chapter 3 | Stacks and Queues--实现一个函数返回栈中的最小值,时间复杂度为O(1)
- 算法2_实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值,时间复杂度都为O(1)(keep it up)
- 在O(1)时间复杂度中,求栈中的最小元素
- 试设计一个算法,将数组A(0..n-1)中的元素循环右移k位,并要求空间复杂度为O(1),时间复杂度为O(n)。
- 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。时间复杂度都是O(1)
- 设计一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作
- 【C++】返回栈中最小的元素,要求时间复杂度为O(1)
- 011实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值,时间复杂度都为O(1)(keep it up)
- 随笔:设计一个栈结构,使得取出栈中最大值时间复杂度为O(1)
- 实现一个栈,实现入栈,出栈,求最小值,时间复杂度为O(1)
- Java 在栈中以常数时间求出栈中最小元素
- 程序员面试金典: 9.3栈与队列 3.2设计一个栈,除pop与push方法,支持返回栈最小元素min方法,时间复杂度均为O(1)
- 算法设计:将一个数组分为奇数、偶数左右两个部分,要求时间复杂度为O(n)
- 算法与数据机构学习_第一章.栈和队列_1.设计一个有返回栈中最小元素功能的栈
- 如何判断一个整数数组中是否有重复元素?要求时间复杂度O(n),空间复杂度O(1)
- 构造一个特殊栈,实现方法getmin,返回栈中的最小元素 Python版