您的位置:首页 > 大数据 > 人工智能

leetcode Container With Most Water

2014-08-01 17:37 302 查看
Given n non-negative integers a1, a2,
..., an, where each represents a point at coordinate (i, ai). n vertical
lines are drawn such that the two endpoints of line i is at (i, ai) 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.

两边设一个指针,然后计算area,如果height[i] <= height[j],那么i++,因为在这里height[i]是瓶颈,j往里移只会减少面积,不会再增加area。

这是一个贪心的策略,每次取两边围栏最矮的一个推进,希望获取更多的水。

可以做简单证明。

如图,L1<R1<R2<L2,那么在L1移动到L2和R1移动到R2的过程中,存在的Lx和Rx都满足Lx < L1, Rx < R1。假设Lx < Rx,那么Lx* d(Rx - Lx) < L1*d(Rx-Lx) < L1 * ( R1 - L1)。若Lx > Rx,则Rx * d(Rx - Lx) < Rx * d(R1 - L1) < L1 * d(R1 - L1) (因为Rx,Lx都小于L1<R1)。直观的想就是,如果宽度减少,同时左右两侧的板都比原来的还要矮,怎么可能容纳更多的水呢?



class Solution {
public:
int maxArea(vector<int> &height) {
int i = 0;
int j = height.size()-1;
int max = 0;
int area = 0;
while(i<j) {
area = (j-i) * (height[j]>=height[i]? height[i] : height[j]);
if(area>max)
max = area;
if(height[j]>=height[i])
i++;
else
j--;
}
return max;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode