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
原创粉丝点击