zoukankan      html  css  js  c++  java
  • 【LeetCode】155. Min Stack

    题目:

    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.

    提示:

    这道题可以通过使用两个stack实现对最小值的记录,每次push进来一个数后,比较该数是否小于当前最小值,如果小于的话就push进保存最小值的stack当中,由于stack“先进后出”的特性,因此后面Push进来的较大的值并不会影响最小值的判断,因为这个较大的值会在之前push进来的较小的值之前pop出去。

    另外还可以只使用一个stack,具体的方法就是在stack中存放pair,每个pair的first存放的是值,second存放的是若当前pair在顶部状态时的最小值。

    代码:

    2stack:

    class MinStack {
        stack<int> s;
        stack<int> min;
    public:
        void push(int x) {
            if (min.empty() || x <= getMin()) min.push(x);
            s.push(x);
        }
    
        void pop() {
            if (s.top() == min.top()) min.pop();
            s.pop();
        }
    
        int top() {
            return s.top();
        }
    
        int getMin() {
            return min.top();
        }
    };

     1stack:

    class MinStack {
        typedef pair<int,int> pairt;
        deque<pairt> stack;
    public:
        void push(int x) {
            if (stack.size())
                stack.push_back(make_pair(x, min(x,getMin())));
            else 
                stack.push_back(make_pair(x, x));
        }
    
        void pop() {
            stack.pop_back();
        }
    
        int top() {
            return stack.back().first;
        }
    
        int getMin() {
            return stack.back().second;
        }
    };
  • 相关阅读:
    java继承中的初始化顺序
    java可访问修饰符
    java简单数据类型转化
    java运算符优先级
    面向切面编程的例子
    什么是面向切面编程
    return 的使用
    通过修改my.ini配置文件来解决MySQL 5.6 内存占用过高的问题
    spring 注入使用注解(不用xml)
    spring在扫描包中的注解类时出现Failed to read candidate component错误
  • 原文地址:https://www.cnblogs.com/jdneo/p/4794516.html
Copyright © 2011-2022 走看看