LeetCode-Min Stack-解题报告

来源:互联网 发布:君子知怕的论证过程 编辑:程序博客网 时间:2024/05/28 15:52

原题链接https://leetcode.com/problems/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. 
实现一个栈,与其他栈不同的地方在于getMin方法,在o(1)的复杂度下获得栈中的最小值。


我用两个栈,一个栈Stack放原本的元素,另一个栈Min 存放最小值。

Stack的入栈情况不变。

Min栈

入栈情况。

如果栈为空,当入栈的时候,直接将元素push到Min

如果栈不为空,当入栈的元素<= Min.top(),入栈,反之则不入栈。

出栈情况

如果出栈元素和Min.top()相等,则Min.pop(),,其他情况Min不出栈。


因为栈的特点是FILO,所以当其他比Min.top()大的元素入栈是不会影响到最小值的。因此Min.top()总是Stack中当前的最小值。


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


0 0
原创粉丝点击