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.

解析:题目要求设计一个栈,实现的功能包括入栈、出栈、获取栈顶元素和返回栈的最小值。

解法1:

先看一个比较麻烦的解法,采用双向队列实现,具体代码如下:

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        stacks.clear();
        min_num = INT_MAX;
    }
    
    void push(int x) {
        stacks.push_back(x);
        if(x < min_num)
            min_num = x;
    }
    
    void pop() {
        stacks.pop_back();
        min_num = INT_MAX;
        for(auto it = stacks.begin(); it != stacks.end(); it ++)
        {
            if(*it < min_num)
                min_num = *it;
        }
    
    }
    
    int top() {
        return stacks.back();
    }
    
    int getMin() {
        return min_num;
    }
    int min_num;
    deque<int> stacks;
};

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

这个方法代码比较繁琐,并且存在可优化空间。下面看一个更简洁的代码。

解法2:题目中要求的栈,比原来的栈增加了返回最小值的功能,采用两个栈来实现,一个正常的存放元素,另一个用来存放最小值。具体代码如下:

class MinStack {
public:
    /** initialize your data structure here. */
    stack<int> s1;//存放正常元素
    stack<int> s2;//存放最小值
    MinStack() {
        
    }
    
    void push(int x) {
        s1.push(x);
        if(s2.empty() || x <= getMin())//如果出现新的最小值,则入栈s2
            s2.push(x);
    }
    
    void pop() {
        if(getMin() == s1.top())//如果当前出栈的元素是最小值,则s2同时出栈
            s2.pop();
        s1.pop();
    }
    
    int top() {
        return s1.top();
    }
    
    int getMin() {
        return s2.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();
 */

参考:https://leetcode.com/problems/min-stack/discuss/49016/C%2B%2B-using-two-stacks-quite-short-and-easy-to-understand

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据