码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Min Stack

时间:2017-12-06 21:58:45      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:new   trie   另一个   ted   使用   example   param   instant   removes   

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.

 

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

最小栈,要求getMin()为检索当前stack中的最小值。

每次添加元素时用minValue来维护一个最小值

在弹出元素时,如果弹出的是最小元素,则需要在弹出后的stack中找出最小值,因为stack不能遍历,所以使用另一个tmpStack来存储原stack中弹出的每一个值找出最小元素。在将tmpStack中的值再传给原stack中。权当是一个遍历。

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        minValue = INT_MAX;
    }
    
    void push(int x) {
        s.push(x);
        minValue = min(minValue, x);
    }
    
    void pop() {
        int tmp = s.top();
        s.pop();
        if (tmp >= minValue) {
            int minVal = INT_MAX;
            while (!s.empty()) {
                tmpS.push(s.top());
                minVal = min(minVal, s.top());
                s.pop();
            }
            minValue = minVal;
        }
        while (!tmpS.empty()) {
            s.push(tmpS.top());
            tmpS.pop();
        }
        
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
        return minValue;
    }
    
private:
    stack<int> s;
    stack<int> tmpS;
    int minValue;
};
// 29 ms
/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

 

[LeetCode] Min Stack

标签:new   trie   另一个   ted   使用   example   param   instant   removes   

原文地址:http://www.cnblogs.com/immjc/p/7994639.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!