Leetcode力扣刷题:11.盛水最多的容器

盛水最多的容器

本题很明显用双指针法
而且要明确一点,本题是要返回一个面积值,所以我们只需要先设定一个初始面积值,后面求得的面积值不断与其相比较,取最大就好。
双指针,分别指向数组的两端。
把数字具象成一根根柱子,我们的指针柱子之前游走。
一个容器能盛水多少,取决于最短的那根柱子有多高,所以我们需要尽力移动指向较短柱子的指针,不断换长柱子,就能增大面积。
为了方便比较,单独写一个求面积的函数。

int Area(int bottom, int h1, int h2)
{
	if (h1 > h2)
		return bottom * h2;
	else
		return h1 * bottom;
}
int maxArea(int* height, int heightSize) {
	int left = 0, right = heightSize - 1;
	int bottom = right - left;
	int area=Area(bottom,height[left],height[right]);
	int res = area;
	while (left < right)
	{
		bottom = right - left;
		area = Area(bottom, height[left], height[right]);
		if (area > res)
			res = area;
		if (height[right] < height[left])
			right--;
		else
			left++;
	}
	return res;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值