1. 程式人生 > >[LeetCode] Min Stack

[LeetCode] Min Stack

minstack 使用 ant init rem ctu str all 如果

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