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 and n is at least 2.
解题思路:注意测试样例会出现高度为0的情况.
解法一:暴力枚举,O(n^2),47/49Passed,果断超时
class Solution {
public:
int min(int a,int b)
{
return a<b?a:b;
}
int maxArea(vector<int>& height)
{
int len = height.size(), mmax = 0, t_sum = 0;
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
int tmin = min(height[i],height[j]), tmax = max(height[i],height[j]);
if(tmin == 0)
{
continue;
}
t_sum = 0;
t_sum += (j-i)*tmin;
if(t_sum > mmax)
{
mmax = t_sum;
}
}
}
return mmax;
}
};
解法二:从两端向中间枚举,每次比较面积与最优解的大小,更新最优解.
若height[L]< height[R],L++;否则R–;
证明过程:
假设这个算法找到的解不是最优解.那么存在hl,hr,使得这两个高度组成的矩形面积最大.那么我们算法在执行过程中肯定先遇到了其中的某个,但没有同时遇到.假设算法执行时遇到了hl(并且假设hl高度更大,不然可以换成hr).他肯定还没有遇到hr,不然最优解已经出现并更新.那么此时若hl继续移动,肯定不会同时遇到了,假设此时hl不移动.但是由题意可知,hl不移动的情况只有两种:
1.另一个指针也指向hl,两指针相遇,算法结束.
2.另一指针指向了ht,并且ht的值不必hl小.此时hl要移动.
那么矛盾出现了,既然hl是hl hr中较大者,现在遇到了ht,并且组成的矩形的长和宽都不比hl,hr组成的小,面积不小于它,那么与hl,hr为最优解矛盾.
所以算法的正确性得以证明.
//19ms AC
class Solution {
public:
int min(int a,int b)
{
return a<b?a:b;
}
int maxArea(vector<int>& height)
{
int len = height.size(), mmax = 0, t_sum = 0;
int left = 0, right = len-1;
while(left < right)
{
int tmin = min(height[left],height[right]);
t_sum = (right-left)*tmin;
if(t_sum > mmax)
{
mmax = t_sum;
}
if(height[left] < height[right])
{
left++;
}
else
{
right--;
}
}
return mmax;
}
};