leetcode-155-Min Stack

题目描述:

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.

 

要完成的函数:

class MinStack {
public:

  MinStack()

  void push(int x)

  void pop() 

  int top() 

  int getMin()

}

 

说明:

1、这道题目让我们设计一个栈,支持常规的入栈、出栈、读出栈顶元素的操作,同时支持时间复杂度为O(1)的读出栈内最小元素的操作。

2、原本要定义一个数组,但是数组自己动态定义比较麻烦,于是偷懒,使用了vector来实现。

3、时间复杂度有限制,最容易想到的解决办法就是增加空间复杂度,多定义一个vector来使用。解决问题。

 

代码:(本代码不支持空栈的栈顶元素读出和空栈的元素出栈,以及空栈的读出最小元素,只是一个简易的代码)

class MinStack {
public:
    vector<int>array;
    vector<int>min;
    MinStack() 
    {
        min.push_back(INT_MAX);
    }
    
    void push(int x)
    {
        if(x<min.back())
            min.push_back(x);
        else
            min.push_back(min.back());
        array.push_back(x);
    }
    
    void pop() 
    {
        array.pop_back();
        min.pop_back();
    }
    
    int top() 
    {
        return array.back();
    }
    
    int getMin() 
    {
        return min.back();
    }
};

 

posted @ 2018-04-09 21:53  chenjx85  阅读(775)  评论(0编辑  收藏  举报