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

155. Min Stack

时间:2020-04-21 23:45:18      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:最小   shell   new   ret   const   思路   time   opera   ons   

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

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

155. Min Stack

标签:最小   shell   new   ret   const   思路   time   opera   ons   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12748844.html

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