zoukankan      html  css  js  c++  java
  • leetcode

    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.
             
    class MinStack {
    public:
    	struct Node
    	{
    		int val;
    		int cntEmlem;
    		Node(int value,int count) : val(value),cntEmlem(count){}
    	};
        void push(int x) {
    		stk.push(x);
    		if(minStk.empty() || x < minStk.top().val)
    		{
    			Node n(x,1);
    			minStk.push(n);
    		}
    		else
    		{
    			Node n = minStk.top();
    			n.cntEmlem++;
    			minStk.pop();
    			minStk.push(n);
    		}
        }
    
        void pop() {
    		stk.pop();
    		Node n = minStk.top();
    		minStk.pop();
    		n.cntEmlem--;
    		if(n.cntEmlem > 0)
    		{
    			minStk.push(n);
    		}
        }
    
        int top() {
    		return stk.top();
        }
    
        int getMin() {
    		return minStk.top().val;
        }
    private:
    	std::stack<int> stk;
    	std::stack<Node> minStk;
    };

    版权声明:本文博主原创文章。博客,未经同意不得转载。

  • 相关阅读:
    DOM getElementById
    百度之星2014
    游艇租借
    2014年acm亚洲区域赛·鞍山站
    UVALive 4255 Guess
    UVA 10054 The Necklace
    UVA 10047 The Monocycle
    UVA 11624 Fire!
    第九届黑龙江省赛
    剑指offer系列31-----二叉树的下一个节点
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/4822919.html
Copyright © 2011-2022 走看看