155. Min Stack

来源:互联网 发布:牦牛壮骨粉的功效 知乎 编辑:程序博客网 时间:2024/05/15 09:40

题目

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.
分析

一开始用vector保存元素,但是返回min的时候需要排序和查找,比较耗时,所以用两个栈,一个保存压入的元素,一个保存最小值,即当压入元素比当前栈顶元素小时压入该元素进最小值的栈,返回最小值时只需要返回当前栈顶元素;当弹出元素时,如果与最小值栈顶元素相等,则最小值栈顶元素也要弹出。

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


0 0
原创粉丝点击