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;
};
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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- C++ Custom Control控件向父窗体发送对应的消息
- C++中拷贝构造函数的应用详解