LeetCode 155. 最小栈 哈希 栈

地址 https://leetcode-cn.com/problems/min-stack/

设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
 

示例:

输入:
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

输出:
[null,null,null,null,-3,null,0,-2]

解释:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> 返回 -3.
minStack.pop();
minStack.top();      --> 返回 0.
minStack.getMin();   --> 返回 -2.
 

提示:

pop、top 和 getMin 操作总是在 非空栈 上调用。

 

解答

算法1

使用栈记录最小栈的基本操作

最小值则考虑一个方便搜索排序的结构体,那么考虑map。

unordered_map则不行,因为他是哈希实现的无法排序.

最大最小堆则不方便删除,也不考虑

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> st;
    map<int,int> mm;
    MinStack() {

    }

    void push(int x) {
        st.push(x);
        mm[x]++;
    }

    void pop() {
        int val =st.top();
        st.pop();
        mm[val]--;
    }

    int top() {
        return st.top();
    }

    int getMin() {
        auto it = mm.begin();
        while(it!=mm.end() && it->second == 0) it++;

        if(it!=mm.end()) return it->first;
        return -1;
    }
};
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/14137783.html