用两个栈实现队列&&旋转非递减数列的最小值
来源:互联网 发布:tcp默认端口号 编辑:程序博客网 时间:2024/05/24 04:17
用两个栈实现队列,比较基础的一道题目了,关键是template的运用。代码如下
#include<iostream>#include<string>#include<stack>using namespace std;template<typename T>class MyQueue{public:void push(T n){a.push(n);}void pop(){if(!b.empty())b.pop();else if(!a.empty()){while(!a.empty()){T n = a.top();a.pop();b.push(n);}b.pop();}throw new exception("queue is empty");}T head(){if(!b.empty())return b.top();else if(!a.empty()){while(!a.empty()){T n = a.top();a.pop();b.push(n);}return b.top();}throw new exception("queue is empty");}bool empty(){if(a.empty()&&b.empty())return true;return false;}private:stack<T> a;stack<T> b;};int main(){MyQueue<int> myqueue;myqueue.push(1);myqueue.push(2);myqueue.push(3);myqueue.push(4);while(!myqueue.empty()){int n = myqueue.head();printf("%d",n);myqueue.pop();}myqueue.pop();system("PAUSE");return 0;}
旋转非递减数列的最小值。既然是非递减数列,可以考虑二分搜索,旋转之后有两个非递减序列,最小值在后面的递减序列里,一步步的缩小范围。但要注意二分搜索应用时递增序列,如果beg,mid,end三个位置对应的数组值相同,则没法划分范围,必须顺序查找。
这样就是log(n)的解法,当然最简单的o(n)也很容易,就是按顺序查找。代码如下
#include<iostream>#include<string>#include<stack>using namespace std;int getorder(int a[],int beg,int end){int mina = a[beg];for(int i = beg+1;i<=end;i++)if(a[i]<mina)mina = a[i];return mina;}int getmin(int a[],int length){int beg = 0;int end = length-1;int mid = beg;while(a[beg] >= a[end]){if(end-beg == 1){mid = end;break;}mid = (beg+end)>>1;if(a[beg] == a[mid] && a[mid] == a[end]){return getorder(a,beg,end);}if(a[mid] >= a[beg])beg = mid;else if(a[mid] <= a[end])end = mid;}return a[mid];}int main(){int a[] = {4,5,6,7,8,1,2,3};int n = getmin(a,8);printf("%d\n",n);system("PAUSE");return 0;}
0 0
- 用两个栈实现队列&&旋转非递减数列的最小值
- 用两个栈实现队列、旋转数组的最小数、斐波那契数列、青蛙跳台阶、矩形覆盖 --漫漫算法路 刷题篇
- 链式表的非递减数列合并
- 顺序表的非递减数列合并
- 两个非递减数组的合并
- 剑指Offer笔记—— 用两个栈实现队列 旋转数组的最小数字
- 旋转数组的最小数字(非递减数组)
- 【链表】merge两个非递减的链表为一个非递减的链表
- 基于单链表的两个非递减有序表的合并
- 两个非递减有序表的合并_Page_39
- PAT 1029. Median (25)(找出俩个非递减数列的公共的中值,我用优先队列做的)
- 用两个栈实现队列的源代码
- 用两个栈实现队列的功能
- 用两个栈实现队列的过程
- 用两个栈实现队列的操作
- 用两个栈实现队列的操作
- 用两个栈实现的队列
- uva1427 - Parade 单调队列 维护递减数列
- UVA - 10405 Longest Common Subsequence(动态规划:LCS)
- leetcode Add Two Numbers
- 教练是协助者
- 黑马程序员-JAVA if语句练习
- linux间通讯
- 用两个栈实现队列&&旋转非递减数列的最小值
- sqlite3
- My97DatePicker时间控件使用
- Linux python使用mysql数据库
- 时间复杂度的估算
- C++杂谈之关于文件操作的若干问题
- 块设备(一)
- [转]深入理解abstract class和interface
- ffmpeg废弃的接口