[LeetCode]Min Stack

来源:互联网 发布:c语言考试卷 编辑:程序博客网 时间:2024/06/06 14:01

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.

实现栈的常规操作,其中getMin()要求用常数时间获取栈中当前最小元素。


分析:

用空间换时间:在栈A(原本的栈)外多用一个向栈顶递减的栈B

    插入值时如果值要小于或等于栈B顶元素,就将它同时压入栈AB,否则只压入AA的元素出栈时如果栈顶元素恰好等于B栈顶元素则同时B出栈。


class MinStack {public:void push(int x) {realStk.push(x);if (miniStk.empty() || x <= miniStk.top())miniStk.push(x);}void pop() {if (realStk.top() == miniStk.top())miniStk.pop();realStk.pop();}int top() {return realStk.top();}int getMin() {return miniStk.top();}private:stack<int> realStk;stack<int> miniStk;};


0 0
原创粉丝点击