155. Min Stack

Problem:

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 1:

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

Constraints:

  • Methods pop, top and getMin operations will always be called on non-empty stacks.

思路

定义一个栈与保存最小值的栈。最小值栈与栈同时push和pop,添加值的时候,与最小值栈顶元素比较,若新值小则将新值压入最小值栈,否则将最小值栈顶的元素再次压栈。

Solution (C++):

stack<int> stk, min_stk;
/** initialize your data structure here. */
MinStack() {
    
}

void push(int x) {
    stk.push(x);
    if (min_stk.empty() || x < min_stk.top())
        min_stk.push(x);
    else  min_stk.push(min_stk.top());
}

void pop() {
    if (!stk.empty() && !min_stk.empty()) {
        stk.pop();
        min_stk.pop();
    }
}

int top() {
    if (stk.empty())  return -1;
    return stk.top();
}

int getMin() {
    if (min_stk.empty())  return -1;
    return min_stk.top();
}

性能

Runtime: 40 ms  Memory Usage: 14.5 MB

思路

也是定义一个data栈与保存最小值的栈,但是与前一种方法不同,入栈时检查新值小于等于最小值栈顶的值,如果是则压入最小值栈,否则不压入最小值栈。pop时判断data栈顶值是否等于最小值栈顶值,若是则最小值栈顶弹出,否则不弹出。

Solution (C++):

stack<int> stk, min_stk;
/** initialize your data structure here. */
MinStack() {
    
}

void push(int x) {
    stk.push(x);
    if (min_stk.empty() || x <= min_stk.top())
        min_stk.push(x);
}

void pop() {
    if (!stk.empty()) {
        if (stk.top() == min_stk.top())  min_stk.pop();
        stk.pop();
    }
}

int top() {
    if (stk.empty())  return -1;
    return stk.top();
}

int getMin() {
    if (min_stk.empty())  return -1;
    return min_stk.top();
}

性能

Runtime: 44 ms  Memory Usage: 14.3 MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12748844.html