|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-5-8 18:04 编辑
题目描述:
- 定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
-  
- 示例:
- MinStack minStack = new MinStack();
- minStack.push(-2);
- minStack.push(0);
- minStack.push(-3);
- minStack.min(); --> 返回 -3.
- minStack.pop();
- minStack.top(); --> 返回 0.
- minStack.min(); --> 返回 -2.
-  
- 提示:
- 各函数的调用总次数不超过 20000 次
-  
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/bao-han-minhan-shu-de-zhan-lcof
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- #include <iostream>
- #include <stack>
- using namespace std;
- class MinStack {
- private:
- stack<int> temp1;
- stack<int> temp2;
- public:
- /** initialize your data structure here. */
- MinStack() {
- }
-
- void push(int x) {
- temp1.push(x);
- if(temp2.empty() || temp2.top() >= x){
- temp2.push(x);
- }
- }
-
- void pop() {
- if(temp1.empty()) return;
- if(temp1.top() == temp2.top()) temp2.pop();
- temp1.pop();
- }
-
- int top() {
- return temp1.top();
- }
-
- int min() {
- return temp2.top();
- }
- };
- int main(void){
- MinStack temp;
- temp.push(2);
- temp.push(3);
- temp.push(1);
- cout << temp.min() << endl;
- cout << "----------" << endl;
- temp.pop();
- cout << temp.min() << endl;
- cout << "----------" << endl;
- return 0;
- }
复制代码
注意事项:
1.用temp2的顶端存储最小值。 |
|