您的位置:首页 > 其它

笔试题目汇总

2014-09-22 18:10 239 查看
一、已知数组A[],实现数组B[];使得B[i]=A[0]*A[1]...*A[i-1]*A[i+1]...*A[n-1]
要求:
1)不能使用除法
2)时间复杂度为O(n)
3)空间复杂度为O(1)

#include<iostream>
#include<stack>
using namespace std;
class minStack{
private:
stack<int> myStack;
stack<int> helpStack;
public:
void pop();
void push(int i);
int top();
int getMin();
};

void minStack::pop(){
if(!myStack.empty()&&!helpStack.empty()){
myStack.pop();
helpStack.pop();
}
}

void minStack::push(int i){
myStack.push(i);
if(helpStack.empty()){
helpStack.push(i);
return;
}
int top=helpStack.top();
if(top<i){
helpStack.push(top);
}else{
helpStack.push(i);
}

}

int minStack::top(){
if(!myStack.empty()){
return myStack.top();
}
}

int minStack::getMin(){
if(!helpStack.empty()){
return helpStack.top();
}
}

int main(){
minStack test;
test.push(2);
test.push(1);
test.push(3);
cout<<test.top();
cout<<test.getMin()<<endl;
}


栈中取最小值,时间复杂度O(1)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: