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

LeetCodeOJ_11_m_Container With Most Water

2015-12-08 17:45 176 查看
答题链接

题目:

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.

Tags Array Two Pointers

Similar Problems (H) Trapping Rain Water

分析:

方法:

定义两个指针,从左右两端向中间移动,如果左线短于右线,则移动左边,反之移动右边,并记录当前得到的最大容积。

为什么此方法可行?

(1)初始:令 left = 0,right = size-1,此时,maxArea 是以 0 为左边界,size-1 为右边界时的最大容量。

(2)保持:当 left = L,right = R,此时,maxArea 是以 L 及其左边的数为左边界,R 及其右边的数为右边界时,所能得到的最大容量,也就是说:

maxArea >= width* height,

其中,width = R - L,height = min(a[L], a[R])

接下来,我们要怎么移动指针呢?

要注意,我们肯定不能 L- - 或者 R++ ,因为maxArea 是以L及其左边的数为左边界,R及其右边的数为右边界时,所能得到的最大容量,所以,我们只能L++ 或者 R–。

**当 a[L] < a[R] 时,width = R - L,height = a[L]。

a:如果右指针左移(R - -),那么:

width’ = R-L-l < width

height’ = min( a[R-1], a[L] ) < height

Area[ L, R-1 ] = width’ * height’ < maxArea

也就是说,R- - 操作后,得到的新容量 Area[ L, R-1 ] 一定小于我们当前已经获得的最大容量。

那么,有没有可能 R -1 和某一个左边界M(M < L)构成的容量值Area[ M, R-1 ] 大于maxArea呢?

不可能!为什么呢?

b:如果左指针右移(L++),那么:

width’ = R-L-l < width

height’ = min( a[L+1], a[R] ) ,有可能会大于height

newArea = width’ * height’ ,如果 newArea > maxArea,更新 maxArea = newArea。

那么,有没有可能 L+1 和某一个右边界M(M > R)构成的容量值Area[ L+1, M ] 大于maxArea呢?

不可能!为什么呢?

也就是说,当a[L] < a[R]时,通过左指针右移,令 left = L+1,并更新maxArea,可以使得maxArea 是以 L+1 及其左边的数为左边界,R 及其右边的数为右边界时,所能得到的最大容量。

**当a[L] < a[R]时,同理可得,只能右指针左移,另 right = R-1,并根据计算结果更新maxArea,可以使得maxArea 是以 L 及其左边的数为左边界,R-1 及其右边的数为右边界时,所能得到的最大容量。

(3)循环:循环处理,直到left>right时停止,就可以得到最终的最大容量值。

代码:

class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea = 0;
int left = 0, right = height.size() - 1;

while (left < right)
{
int area = (right - left) * min(height[left], height[right]);

if (area > maxArea)
maxArea = area;

if (height[left] < height[right])
{
++left;
}
else
{
--right;
}
}

return maxArea;
}
};


结果:



总结:

学会分析数据内在规律,节省运行时间。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: