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.
题目有点长,大致意思就是装最多的水,n个非负整数表示桶的左右高度,能装多少水是由左右高度的最小值和下面的宽度决定的,Vol=(j-1)*min(aj,ai).
如果用群举的话会超时,所以要定义两个指针,一个从前,一个从后,但是根据条件移动位置。
class Solution {
public:
int maxArea(vector<int>& height) {
int result = 0;
int i=0, j=height.size()-1;
while(i<j)
{
int temp = (j-i)*min(height[i],height[j]);
if(height[i]<height[j])
{
i++;
}
else
{
j--;
}
if(temp>result)
result = temp;
}
return result;
}
};