Min Stack
来源:互联网 发布:网络安全管理培训 编辑:程序博客网 时间:2024/04/29 20:32
第一反应是实现一个优先队列,这样可以在O(1)的时间内找到最小值,但这并不是题目想要的答案,题目只需要一个stack,其附加功能是能在O(1)内找到最小值,如果用优先队列则无法保证stack的性质。实现优先队列的代码如下:
class MinStack {public: vector<int> heap; int sz; MinStack():sz(0){}bool empty(){return sz==0;} void push(int x) {if(sz<heap.size()){heap[sz++]=x;}else{heap.push_back(x);sz++;} buttonUpAdjust(); } void pop() { heap[0]=heap[sz-1]; sz--; topDownAdjust(); } int top() { return heap[0]; } int getMin() { return heap[0]; } void topDownAdjust() { int curPos=0; while(curPos<sz) { int left=leftChild(curPos); int right=rightChild(curPos); int minPos=left; if((left<sz)||(right<sz)) { if((right<sz)&&(heap[right]<heap[left])) { minPos=right; } if(heap[minPos]<heap[curPos]) { int tmp=heap[minPos]; heap[minPos]=heap[curPos]; heap[curPos]=tmp; curPos=minPos; } else { break; } } else { curPos=left; } } } void buttonUpAdjust() { int pos=sz-1; while((pos!=0)&&(heap[father(pos)]>heap[pos])) { int tmp=heap[father(pos)]; heap[father(pos)]=heap[pos]; heap[pos]=tmp; pos=father(pos); } } int father(int pos) { return (pos-1)/2; } int leftChild(int pos) { return 2*pos+1; } int rightChild(int pos) { return 2*pos+2; }};
满足题目要求的代码如下:
class MinStack {public: stack<int> stk; stack<int> minstk; void push(int x) { stk.push(x); if(minstk.empty()||minstk.top()>=x) { minstk.push(x); } } void pop() { int tmp=stk.top(); if((!minstk.empty())&&(minstk.top()==tmp)) { minstk.pop(); } stk.pop(); } int top() { return stk.top(); } int getMin() { return minstk.top(); }};
0 0
- min stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- Min Stack
- 一鍵備份/還原文件/文件夾時間
- jQuery的DataTables插件的使用方法
- python 中需要注意的地方
- ClassLoader与System学习笔记
- 挣值分析
- Min Stack
- 解决oracle语句中 含数字的字符串按数字排序问题
- 字符反转以及涉及到的 StringBuilder
- uva 10534 Wavio Sequence nlogn方法
- beaglebone black接入ds18b20并通过网络上传数据
- 中国银联对圈存脚本及冲正机制的建议
- AndroidStudio创建TV-APP,出现Error:(28, 13) Failed to resolve: com.squareup.picasso:picasso:2.5.0 的解决
- Linux下ELF共享库使用摘记
- DynamicQueryable基于Linq的动态查询