155. Min Stack
2016-03-20 16:19
337 查看
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.
题意:实现一个最小栈,要求具有以上四个功能,且能常量时间返回检索最小值元素的功能。
思路:一个数组用来存值,一个数存最小值。注意:数组里存的是存入值与最小值的差,所以可能越界,要用long long类型保存差值。
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.
题意:实现一个最小栈,要求具有以上四个功能,且能常量时间返回检索最小值元素的功能。
思路:一个数组用来存值,一个数存最小值。注意:数组里存的是存入值与最小值的差,所以可能越界,要用long long类型保存差值。
class MinStack { public: void push(int x) { if (val.empty()){ val.push_back(0); min = x; } else{ val.push_back((long long)x - min); if (x < min) min = x; } } void pop() { if (!val.empty()){ int index = val.size() - 1; if (val[index] < 0){ min -= val[index]; val.erase(val.begin()+index); } else{ val.erase(val.begin() + index); } } } int top() { int index = val.size() - 1; if (val[index] < 0) return min; else{ return min + val[index]; } } int getMin() { if (!val.empty()) return min; else return -1; } private: vector<long long> val; int min; };
相关文章推荐
- Activity过渡动画
- 第三周学习进度条
- 猎豹MFC--字体颜色对话框CFontDialog CColorDialog CRichEdit
- I-think-3
- Spring各种依赖注入注解的区别
- runtime
- JAVa面向对象--反射
- resteasy框架之PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy
- 快速排序
- 设计模式——单例模式
- 一道取球概率题
- caffe入门学习:caffe.Classifier的使用
- 类类型
- 介绍下XML
- Redis事件管理(一)
- 猎豹MFC--状态栏CStatusBar
- BZOJ2223PATULJCI
- ubuntu 安装mono Fiddler后The proxy server is refusing connections
- 归并排序
- C++中引用传递与指针传递区别