[Leetcode] 716. Max Stack 解题报告

题目

Design a max stack that supports push, pop, top, peekMax and popMax.

  1. push(x) -- Push element x onto stack.
  2. pop() -- Remove the element on top of the stack and return it.
  3. top() -- Get the element on the top.
  4. peekMax() -- Retrieve the maximum element in the stack.
  5. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.

Example 1:

MaxStack stack = new MaxStack();
stack.push(5); 
stack.push(1);
stack.push(5);
stack.top(); -> 5
stack.popMax(); -> 5
stack.top(); -> 1
stack.peekMax(); -> 5
stack.pop(); -> 1
stack.top(); -> 5

Note:

  1. -1e7 <= x <= 1e7
  2. Number of operations won't exceed 10000.
  3. The last four operations won't be called when stack is empty.

思路

我们定义两个数据结构:1)list用来模拟栈,这样可以实现push,pop和top;2)map::iterator>>,用来实现peekMax和popMax,因为我们可以从map中利用O(1)的时间复杂度得到最大的数,而由于我们在map中也同时保存了各个数对应的迭代器,所以也可以在O(1)的时间复杂度内删除掉list中的内容。

这样的话,可以保证push和pop的时间复杂度为O(logn),top,peekMax,popMax的时间复杂度都为O(1)。整个算法的空间复杂度为O(n)。我感觉应该是最优的算法了。

代码

class MaxStack {
public:
    /** initialize your data structure here. */
    MaxStack() {
        
    }
    
    void push(int x) {
        auto it = l.insert(l.end(), x);
        m[*it].push_back(it);
    }
    
    int pop() {
        auto it = l.end();
        --it;
        int value = *it;
        m[*it].pop_back();
        if (m[*it].empty()) {
            m.erase((*it));
        }
        l.erase(it);
        return value;
    }
    
    int top() {
        return *(l.rbegin());
    }
    
    int peekMax() {
        return m.rbegin()->first;
    }
    
    int popMax() {
        auto it = m.rbegin()->second.back();
        int value = m.rbegin()->first;
        m.rbegin()->second.pop_back();
        if (m.rbegin()->second.empty()) {
            m.erase(m.rbegin()->first);
        }
        l.erase(it);
        return value;
    }
private:
    list l;
    map::iterator>> m;
};

/**
 * Your MaxStack object will be instantiated and called as such:
 * MaxStack obj = new MaxStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.peekMax();
 * int param_5 = obj.popMax();
 */

你可能感兴趣的:(IT公司面试习题)