【leetcode】155. Min Stack

来源:互联网 发布:国家邮政局投诉知乎 编辑:程序博客网 时间:2024/05/16 11:04

一、题目描述

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.

题目解读:写一个栈要有以下功能:push(),pop(),top(),getMin()能取得当前栈中的最小元素


思路:直接用一个栈就可以实现所有的push(),pop(),top()这三个功能,在设置一个栈用来存每加入一个元素时当前的最小元素。因此在每pop一个元素对于min栈也要pop一个元素。


c++代码(52ms,74.75%)

class MinStack {public:    /** initialize your data structure here. */    stack<int> min;    stack<int> result;    void push(int x) {        result.push(x);        if(min.empty())            min.push(x);        else{            if(x<min.top())                min.push(x);            else{                min.push(min.top());            }//else          }//else    }//void        void pop() {        result.pop();        min.pop();    }        int top() {        return result.top();    }        int getMin() {        return min.top();    }};/** * 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(); */


其他代码:

class MinStack {private:    stack<int> s1;    stack<int> s2;public:    void push(int x) {    s1.push(x);    if (s2.empty() || x <= getMin())  s2.push(x);        }    void pop() {    if (s1.top() == getMin())  s2.pop();    s1.pop();    }    int top() {    return s1.top();    }    int getMin() {    return s2.top();    }};



0 0
原创粉丝点击