一道比较简单的Google面试题

来源:互联网 发布:理财收益计算器 软件 编辑:程序博客网 时间:2024/04/25 00:56

/*对现在的栈stack进行改进,加一个min功能,使之能够在常数时间,即O(1)找到栈中最小值.可以对Push(const Type&val) 和 Pop()函数进行修改,但要求其时间复杂度都是O(1).
*/
#include<iostream>
#include<stack>
#include<ctime>
#include<cstdlib>

using namespace std;

template<typename T>
class MyStack
{
private:
   stack<T> master;//主要的栈
   stack<T> slave; //辅助栈
public:
   void MyPush( const T& val )
   {
       if(master.empty())
       {
           master.push(val);
       }
       else
       {
           while(!master.empty())
           {
               T curData = master.top();
               if(curData >= val)
               {
                  master.push(val);
                  break;
               }
               else
               {
                  slave.push(curData);
                  master.pop();
               }
           }
           while(!slave.empty())
           {
               master.push(slave.top());
               slave.pop();
           }
        }
   }
   T MyMin()
   {
      return master.top();
   }
  
};
int main()
{
    MyStack<int> ms;
    int *a = new int[10];
    srand(time(0));
    for(int i = 0; i<10;++i)
    {
        a[i] = rand()%100;
        cout<<a[i]<<"  ";
        ms.MyPush(a[i]);
    }
    cout<<endl;
    int ivalue = ms.MyMin();
    cout<<"The min value is :"<<ivalue<<endl;
   
    delete []a;
    system("pause");
    return 0;
}