题目如下:
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.
一、最简单粗暴的做法,遍历所有可能(i,j),计算出maxArea,时间复杂度O(N2)。
二、思考一下,从两端开始往中间遍历,设i = 0, j = height.size() - 1; 由于是短板决定计算出的面积大小,所以当让坐标往中间走的时候(宽度是递减的),必须移动短的一端。这样才有希望让面积增大,不然的话,由于短板限制,面积肯定随着宽度的减少而递减。
代码如下:
class Solution {
public:
int maxArea(vector<int> &height) {
int area = 0, Max = 0;
int i = 0, j = height.size() - 1;
while (i < j){
if (height[i] > height[j]){
area = height[j] * (j - i);
j--;
}
else{
area = height[i] * (j - i);
i++;
}
if (area > Max)
Max = area;
}
return Max;
}
};