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