题目
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个非负整数a 1,a 2,...,a n,其中每个表示坐标(i,a i)处的点。绘制n条垂直线,使得线i的两个端点在(i,a i)和(i,0)处。找到两条线,它们与x轴一起形成一个容器,使得容器含有最多的水。
注意:您不能倾斜容器,n至少为2。
class Solution {
public:
int maxArea(vector<int>& height) {
int right=height.size()-1;
int area=0,maxarea=0,left=0;
while(left<right){
if(height[left]<height[right]){
area=height[left]*(right-left);
left++;
}
else {
area=height[right]*(right-left);
right--;
}
maxarea=max(maxarea,area);
}
return maxarea;
}
};
分析
做了一段时间leetcode,现在看见vector就想排序,不过这题不能排序
本题可以用一个maxarea储存每一次的水容量,并在这次的循环中通过MAX函数与上一次的容量相比较
而水容量等两条线段中较短的乘以两条线的距离
循环的关键条件在于,每一次循环变动的边应该是较短的那条