一道比较简单的Google面试题
2007-04-09 17:32
381 查看
/*对现在的栈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;
}
*/
#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;
}
相关文章推荐
- 一道不简单又简单的Google面试题
- Java中字符串比较的一道面试题
- google的一道JAVA面试题!!!
- 一道面试题比较synchronized和读写锁
- 一道简单的SQL面试题:查询成绩排名第10到第20的学生
- 一道看似简单的面试题
- 一道有趣的GOOGLE面试题
- 一道简单面试题和霍尔规则
- Google 的一道面试题的解法
- 简单一道排序题,考倒多少读书人!——从华为一道面试题浅谈计算机专业在校大学生该如何学习专业课程,信心百倍挑战就业!
- google一道面试题的扩展——智力挑战
- 一道简单的面试题
- 一道简单而又不简单的面试题
- 一道简单的支付宝面试题
- 一道简单面试题引出的优化方法讨论 (Ⅰ)
- 一道简单的面试题(求较小的值,不能用 比较运算符 if-else ?: while for 内嵌汇编 递归 第三方函数)(zt)
- 解决chrome字体不能小于12px (一道简单的面试题)
- 【C面试】一道简单的C语言面试题的思考——打印星阵
- 摔棋子(摔杯子)问题——解答Google的一道面试题
- 白话经典算法系列之十 一道有趣的GOOGLE面试题