首页 > 其他 > 详细

leetcode155 min stack

时间:2020-05-13 00:06:46      阅读:87      评论:0      收藏:0      [点我收藏+]

Description

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.

Problem

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();

易错点

注意考虑记录指针index永远指向当前元素/下一元素

Code

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
    }
    
    void push(int x) {
        if(s.empty())mini[++index]=x;
        else mini[++index]=min(mini[index],x);
        s.push(x);
    }
    
    void pop() {
        index--;
        s.pop();
    }
    
    int top() {
        return s.top();
    }
    
    int getMin() {
        return mini[index];
    }
private:
    stack<int> s;
    int mini[50000];
    int index=-1;
};

leetcode155 min stack

原文:https://www.cnblogs.com/chanceYu/p/12879700.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!