LeetCode 11.Container With Most Water

题目:

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container.

分析与解答:

n个数,a1到an,每个数代表一个坐标(i,ai),将每个数与各自的(0,ai)坐标相连形成一条垂直于X轴的直线。在这些直线里挑两条,形成一个容器,让这个容器在不倾斜的情况下能装最多的水。

容器的装水量取决于两个因素,一个是两个边最小的那一个的高度,另一个是两个边之间的距离。由于数组是无序的,所以高度是没有规律的因素,必须一个一个遍历,但边的距离是有规律的,所以可以设立头尾两个指针head和end,记下他们的装水量V和边的高度h1,h2,假设h1<=h2。之后往中间进行移动,如果移动较高的那条边,是不可能增加装水量的。所以只能移动较矮的那条边。移动过程中如果碰到比h1还矮的边,也是无法增加装水量的,直到遇到比h1高的边,此时重新计算装水量,如果比V大,则刷新h1,h2;否则继续移动,直到head和end相遇。

class Solution {
public:
    int maxArea(vector<int> &height) {
	int left = 0,  maxArea = 0, right = height.size() - 1;
	while (left < right) {
		maxArea = max(maxArea,
				(right - left) * min(height[left], height[right]));
		if (height[left] < height[right])
			left++;
		else
			right--;
	}
	return maxArea;
    }
};




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值