您的位置:首页 > 编程语言 > C语言/C++

LeetCode-Min Stack-解题报告

2015-07-07 16:01 465 查看
原题链接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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ leetcode