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

leetcode----Container With Most Water

2016-06-01 10:48 483 查看
原地址:https://leetcode.com/problems/container-with-most-water/

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.



(图片参考:http://www.programcreek.com/2014/03/leetcode-container-with-most-water-java/)

题意:一个数组A里面放了n个非负整数a1, a2, ..., an。

然后画线段,将(i, ai)与(i, 0)连接起来。

要求找两个竖直线段,这两个线段与X轴之间形成的这个『|_|』空间的面积最大(这个面积的高,以最短竖直线长度为准)。
分析:

首先这样想,当初始两个指针i指向左端点,j指向右端点的时候,最优解必然出现在i, j之间(包括两者)。

直观上理解是这样的:

每次移动的时候,可以计算的底的长度肯定是减少的。

如果向里移动长一点的『墙壁』,由于接水的面积由底和最短边决定,无论得到的下一个『墙壁』是否增加,接水的面积都不可能增加,只能减少。

那么,如果移动短『墙壁』,得到新的最短『墙壁』则有可能比移动之前大(上限是移动之前的长一点的『墙壁』)。这样还有可能出现面积增大的情况。

只需要记录这个过程中,得到面积的最大值即可。

但是,目前还不知道该如何证明这个方法一定能得到全局最优。

代码实现:

class Solution {
public:
int maxArea(vector<int>& height) {
int ans = 0;
int i = 0, j = height.size() - 1;
int pre_l = height[i];
int pre_r = height[j];
while(i < j){

if(height[i] < height[j])
{
ans = max(ans, (j - i) * height[i]);
i++;
while(pre_l >= height[i] && i < j) i++;

pre_l = height[i];
}
else
{
ans = max(ans, (j - i) * height[j]);
j--;
while(pre_r >= height[j] && i < j) j--;

pre_r = height[j];
}

}

return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息