leetcode - 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.
         
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;
};

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

posted @ 2015-09-20 10:01  lcchuguo  阅读(161)  评论(0编辑  收藏  举报