用两个栈实现队列&&旋转非递减数列的最小值

用两个栈实现队列,比较基础的一道题目了,关键是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;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值