代码改变世界

Find min elements in the Stack

2010-09-25 19:46  wansishuang  阅读(244)  评论(0编辑  收藏  举报

Implement a stack which supports FindMin(),push() and pop(). The probability of the occurrence is equal.

 

Maintain two stacks. In 1st, maintain the values in order of their push event. while in 2nd stack maintain the minimum value till the same index value in 1st stack.
All operations: 0(1).

Example: 1st stack, 2nd stack
push(5)[1stack(5),2stack(5)],push(3)[1stack(5,3),2stack(5,3)],push(7)[1stack(5,3,7),2stack(5,3,3)].
pop will remove(pop) a node from both stacks and will return the pop from 1st stack as answer.

#include <iostream>
#define MAXN 100
using namespace std;

template <typename T>
class Stack
{
public:
    Stack()
    {
        curIndex = -1;
    }
    void push(T x)
    {
        ++curIndex;
        if(curIndex >= MAXN) return;
        if(curIndex == 0 || x < stackMinItem[curIndex-1])
        {
            stackMinItem[curIndex] = x;
        }
        else
            stackMinItem[curIndex] = stackMinItem[curIndex - 1];
        stackItem[curIndex] = x;
    }
    T pop()
    {
        if(curIndex < 0) return -1;
        return stackItem[curIndex--];
    }
    T min()
    {
        if(curIndex < 0) return -1;
        return stackMinItem[curIndex];
    }

private:
    int curIndex;
    int stackItem[MAXN];
    int stackMinItem[MAXN];
};

/**
 * test
 **/
int main()
{
    Stack<int> s;
    s.push(5);
    s.push(2);
    s.push(3);
    s.push(4);
    s.push(1);
    s.push(6);

    cout<< s.min() << endl;
    s.pop();
    cout<< s.min() << endl;
    s.pop();
    cout<< s.min() << endl;
    s.pop();
    cout<< s.min() << endl;
}