2015阿里笔试题
阿里2015招聘实习生笔试题
笔试最后一题,题目大意是:给定一数组,数组中每个元素代表一个宽度为1的墙,求由这些墙能装多少水,输入为[1,0,2,1,0,1,3,2,1,2,1],输出为6.时间复杂度为O(n),空间复杂度为O(1).#include<iostream>
using namespace std;
int Volume(int A[],int n)
{
int p=0,q=n-1,cer,sum;
sum=0;
while(p<q)
{
if(A[p]<=A[q])
{
while(A[p]<=A[p+1])p++;
cer=p;
if(A[p]>A[q]){}
else
{
p++;
while(A[p]<=A[cer]){sum+=A[cer]-A[p];p++;}
}
}
else
{
while(A[q]<=A[q-1])q--;
cer=q;
if(A[p]<=A[q]){}
else
{
q--;
while(A[q]<=A[cer]){sum+=A[cer]-A[q];q--;}
}
}
}
return sum;
}
int main()
{
int a[]={1,0,2,1,0,1,3,2,1,2,1};
int s=Volume(a,11);
cout<<s<<endl;
return 0;
}