题目描述:
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 acontainer, such that the container contains the most water.
Note: You may not slant the container.
Hide Tags Array Two Pointers
分析:
要求两条垂直于x轴的直线与x轴组成的最大容积,仔细分析得知,变量只有长和高,也就转化为求最大面积。长是由两个横坐标的差决定,高是由较小的纵坐标决定。如果x1 < x2,那么面积A表示为 (x2 - x1)* min( height[x1], height[x2] ).
转化为数学问题:求两个数乘积的最大值:如果其中一个数变小,那么只有当另一个数增大的情况下才有可能使乘积变大。于是,可以首先从最大长度开始先计算此时面积,然后往中间靠拢,由于此时长度变小了,那么找到大于当前的高度,计算长度和高度变更后的面积,与变化前的面积比较,更新最大面积。最后得到的最大面积就是所求。
以下是C++实现代码:
/*/27ms*/
class Solution {
public:
int min(int a,int b)
{
return a < b ? a:b;
}
int max(int a,int b)
{
return a > b ? a:b;
}
int maxArea(vector<int>& height)
{
if(height.empty())
return 0;
int size = height.size();
int maxA = 0,lef = 0, rig = size-1;
int k = 0;
while(lef < rig)
{
maxA = max(maxA, min(height[lef],height[rig]) * (rig - lef)) ; //更新最大面积
if(height[lef] > height[rig]) //如果左边的高度小于右边的高度,那么从右边开始收拢,找到第一个大于右边高度的点,更新右边的横坐标
{
k = rig;
while(k > lef && height[k] <= height[rig])
k--;
rig = k;
}
else //如果左边高度小于右边的高度,那么从左边开始收拢,找到第一个大于左边高度的点,更新左边的横坐标
{
k = lef;
while(k < rig && height[k] <= height[lef])
k++;
lef = k;
}
}
return maxA;
}
};