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.
题意:给定n个非负数整数a1, a2, …, an, 每个数代表坐标(i, ai)的一个点。以(i, ai) 和 (i, 0)为线段的端点画了n条垂直的线。 找到其中两条, 使他们和x轴形成的一个容器可以装最多的水。
注意:容器不能倾斜。
思路:两层 for 循环的暴力法会超时。用两个指针从两端开始向中间靠拢,如果左端线段短于右端,那么左端右移,反之右端左移,(为什么?当左端线段L小于右端线段R时,我们把L右移,这时舍弃的是L与右端其他线段(R-1, R-2, …)组成的木桶,这些木桶是没必要判断的,因为这些木桶的容积肯定都没有L和R组成的木桶容积大。这相当于是一个贪心策略!!)直到左右两端移到中间重合,记录这个过程中每一次组成木桶的容积,返回其中最大的。
class Solution {
int MAX(int a,int b)
{
return a>b?a:b;
}
int MIN(int a,int b)
{
return a<b?a:b;
}
public:
int maxArea(vector<int>& height) {
int r=height.size()-1;
int l=0;
int max=0;
while(l<r)
{
max=MAX(max,MIN(height[l],height[r])*(r-l));
if(height[l]<height[r])l++;
else r--;
}
return max;
}
};