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

leetcode-155-Min Stack

时间:2018-04-09 23:18:11      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:解决   div   nim   retrieve   amp   trie   复杂   max   AC   

题目描述:

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

 

leetcode-155-Min Stack

标签:解决   div   nim   retrieve   amp   trie   复杂   max   AC   

原文地址:https://www.cnblogs.com/king-3/p/8763239.html

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