可以随时查找的max栈和max队列——面试
2013-10-30 18:01
169 查看
这是面试中比较常见的题目,max队列也是编程之美里的一道题
对于max的栈,有个比较简单的办法就是,每次入栈前判断栈顶元素与正在入栈的元素哪个大,哪个大就哪个入栈
对于队列,我们知道可以用两个栈来实现,这时,我想到是否可以用栈来维护max的队列
结果是可以的,不过要用三个栈, 1 +2 ,前一个max栈+ (后一个max栈+普通的栈) ,每次寻找max都在前一个max栈和后一个max栈中找,而要更新前一个栈的时候,要把普通的栈来去更新
考虑 1,2,4,3
进1进2进4进3出1出2出4
大4大4大3
View Code
对于max的栈,有个比较简单的办法就是,每次入栈前判断栈顶元素与正在入栈的元素哪个大,哪个大就哪个入栈
对于队列,我们知道可以用两个栈来实现,这时,我想到是否可以用栈来维护max的队列
结果是可以的,不过要用三个栈, 1 +2 ,前一个max栈+ (后一个max栈+普通的栈) ,每次寻找max都在前一个max栈和后一个max栈中找,而要更新前一个栈的时候,要把普通的栈来去更新
考虑 1,2,4,3
进1进2进4进3出1出2出4
大4大4大3
/* 10 push 1 push 2 push 4 push 2 pop max pop max pop max */ #include<iostream> #include<stack> #include<queue> using namespace std; //push //pop //max struct data{ int v; }; stack<data>first,end; stack<data>sta; int main() { int n; while(scanf("%d",&n)!=EOF){ int i,shu;data temp; char str[10]; for(i=1;i<=n;i++){ scanf("%s",&str); if(end.empty()&&(!sta.empty())){ //第二个堆空的时候把第一个普通堆放到第二个堆里 end.push(sta.top()); sta.pop(); first.pop(); while(!sta.empty()){ temp=end.top(); if(temp.v<sta.top().v){ temp=sta.top(); } end.push(temp); sta.pop(); first.pop(); } } if(str[1]=='u'){ scanf("%d",&shu); temp.v=shu; sta.push(temp); if(!first.empty()){ if(first.top().v>temp.v)temp=first.top(); first.push(temp); }else{ first.push(temp); } }else if(str[1]=='o') { end.pop(); }else{//max if(!first.empty()){ temp=first.top(); if(temp.v<end.top().v)temp=end.top(); }else{ temp=end.top(); } printf("%d\n",temp.v); } } } return 0; }
View Code
相关文章推荐
- hdu1024 Max Sum Plus Plus[降维优化好题(貌似以后可以不用单调队列了)]
- 程序员面试题目总结--数组(五)【数组的后面m个数移动为前面m个数、列的前n项数据、判断整数x是否可以表示成n个连续正整数的和、数组中出现奇数次的元素、二维数组中的查找】
- 完成一个学生管理程序,使用学号作为键添加5个学生对象,并可以将全部信息保存在文件中,可以实现对学生信息的学号查找,输出全部学生信息的功能。
- 微软等数据结构+算法面试100题(16)--查找子串
- #面试#螺旋队列
- 华为面试,字串的连接最长路径查找
- 面试时可以提的问题
- 面试-查找(静态查找,动态查找)
- 使用PHP描述顺序查找和二分查找(也叫做折半查找)算法,顺序查找必须考虑效率,对象可以是一个有序数组
- <笔试><面试>编写一个排序函数,实现,既可以排序整形数组,又可以排序字符串。
- ios 中调用函数的方法是消息传递,这个和普通的函数调用的区别是,你可以随时对一个对象传递任何消息,而不需要在编译的时候声明这些方法。所以Objective-C可以在runtime的时候
- 面试时可以向面试官提那些问题
- Windows - 你可以在Windows中做出一个全路径文件名(Fully Qualified File Name)长度超出MAX_PATH=260字节的文件
- poj 1177 又是一道十分恶心到线段树。 主要是用线段树到区间操作。可以用来节省线性查找的时间。 离散化也十分好的一道题。
- hdu 3415 Max Sum of Max-K-sub-sequence(单调队列)
- hdu 3530 Subsequence 单调队列 求最长连续区间,满足条件(m<=max-min<=k)
- 用程序创建数据库并导入宠物信息,并可以实现关键字查找
- 骑驴找马面试难,你可以这样解决!
- 非web java项目部署到linux总结(非打包成jar,配置文件可以随时修改)
- 坚持完成这套学习手册,你就可以去 Google 面试了