阿里的一个笔试题目,求积水体积。

如图题目要求。


#include <iostream>

using namespace std;
int Volume(int * Height,int n);
int main()
{
	int sum = 0;
	int H[11] = {1,2,0,1,0,1,3,1,0,2,1} ;
	sum = Volume(H,11);
	cout<<sum<<endl;
	getchar();
	return 0;

}
int Volume(int * Height,int n)
{
	//要想能够装住水,必须两边高中间低,就像河流,两边高,中间洼才能有水。
	//代码的主要思想:持续寻找从数组两头寻找河的两边高地,先不管中间是否有新的高地,
	//只要目前的高地能够圈住水,那就求出能够最大装水量,以此类推。
	int L = Height[0];
	int R = Height[n-1];
	int temp=0;
	int i = 0;
	int j = n;
	for(i;j-i>0;i++)
	{

		j = n-i-1;

		if(L<Height[i])
		{
			L=Height[i];
		}
		if(R<Height[j])
		{
			R=Height[j];
		}

		if(Height[i]<L&&Height[i]<R)
		{
			if(L<=R)
			{
				temp = temp +(L-Height[i]);
			}
			else
			{
				temp = temp +(R-Height[i]);
			}
		}
		if(Height[j]<L&&Height[j]<R&&i!=j)
		{
			if(L<=R)
			{
				temp = temp +(L-Height[j]);
			}
			else
			{
				temp = temp +(R-Height[j]);
			}
		}
	}
	return temp;
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值